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4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500

"""
Layout engine for positioning and arranging infographic elements
"""
from typing import Dict, List, Tuple, Optional
import math
import logging
from dataclasses import dataclass

logger = logging.getLogger(__name__)

@dataclass
class LayoutElement:
    """Represents a positioned element in the layout"""
    id: str
    type: str
    content: str
    x: int
    y: int
    width: int
    height: int
    priority: int
    styling: Dict

@dataclass
class LayoutGrid:
    """Grid system for organizing layout"""
    columns: int
    rows: int
    cell_width: int
    cell_height: int
    gap: int

class LayoutEngine:
    """Engine for creating and managing infographic layouts"""
    
    def __init__(self):
        """Initialize layout engine"""
        self.current_layout = None
        self.elements = []
        logger.info("Layout engine initialized")
    
    def create_layout(self, styled_content: Dict) -> Dict:
        """
        Create complete layout from styled content
        
        Args:
            styled_content: Content with applied template styling
            
        Returns:
            Complete layout specification
        """
        layout_type = styled_content.get('layout_type', 'Vertical')
        design_specs = styled_content.get('design_specs', {})
        
        # Initialize layout canvas
        canvas_size = design_specs.get('canvas_size', (1080, 1920))
        margins = design_specs.get('margins', {'top': 60, 'bottom': 60, 'left': 60, 'right': 60})
        
        layout = {
            'type': layout_type,
            'canvas_width': canvas_size[0],
            'canvas_height': canvas_size[1],
            'content_area': {
                'x': margins['left'],
                'y': margins['top'],
                'width': canvas_size[0] - margins['left'] - margins['right'],
                'height': canvas_size[1] - margins['top'] - margins['bottom']
            },
            'elements': [],
            'grid': self._create_grid_system(layout_type, canvas_size, margins, design_specs),
            'flow': self._create_flow_system(layout_type)
        }
        
        # Position elements based on layout type
        if layout_type == 'Vertical':
            layout['elements'] = self._create_vertical_layout(styled_content, layout)
        elif layout_type == 'Horizontal':
            layout['elements'] = self._create_horizontal_layout(styled_content, layout)
        elif layout_type == 'Grid':
            layout['elements'] = self._create_grid_layout(styled_content, layout)
        elif layout_type == 'Flow':
            layout['elements'] = self._create_flow_layout(styled_content, layout)
        else:
            layout['elements'] = self._create_vertical_layout(styled_content, layout)
        
        self.current_layout = layout
        return layout
    
    def _create_grid_system(self, layout_type: str, canvas_size: Tuple[int, int], 
                           margins: Dict, design_specs: Dict) -> LayoutGrid:
        """Create grid system for layout"""
        grid_specs = design_specs.get('grid', {'columns': 1, 'rows': 'auto', 'gap': 30})
        
        content_width = canvas_size[0] - margins['left'] - margins['right']
        content_height = canvas_size[1] - margins['top'] - margins['bottom']
        
        columns = grid_specs['columns']
        gap = grid_specs['gap']
        
        cell_width = (content_width - (columns - 1) * gap) // columns
        cell_height = 200  # Default cell height, can be adjusted
        
        return LayoutGrid(
            columns=columns,
            rows=grid_specs.get('rows', 'auto'),
            cell_width=cell_width,
            cell_height=cell_height,
            gap=gap
        )
    
    def _create_flow_system(self, layout_type: str) -> Dict:
        """Create flow system for dynamic positioning"""
        return {
            'direction': 'vertical' if layout_type in ['Vertical', 'Flow'] else 'horizontal',
            'wrap': layout_type == 'Flow',
            'spacing': 'auto',
            'alignment': 'start'
        }
    
    def _create_vertical_layout(self, styled_content: Dict, layout: Dict) -> List[LayoutElement]:
        """Create vertical layout arrangement"""
        elements = []
        current_y = layout['content_area']['y']
        content_width = layout['content_area']['width']
        content_x = layout['content_area']['x']
        
        # Add title
        title = styled_content.get('title', {})
        if title.get('text'):
            title_element = LayoutElement(
                id='title',
                type='title',
                content=title['text'],
                x=content_x,
                y=current_y,
                width=content_width,
                height=self._calculate_text_height(title['text'], title.get('font', ('Arial', 32, 'bold')), content_width),
                priority=10,
                styling=title
            )
            elements.append(title_element)
            current_y += title_element.height + title.get('margin', 40)
        
        # Add sections
        sections = styled_content.get('sections', [])
        for i, section in enumerate(sections):
            section_height = self._calculate_section_height(section, content_width)
            
            section_element = LayoutElement(
                id=f'section_{section.get("id", i)}',
                type='section',
                content=section.get('condensed_text', section.get('content', '')),
                x=content_x,
                y=current_y,
                width=content_width,
                height=section_height,
                priority=section.get('priority', 5),
                styling=section.get('styling', {})
            )
            elements.append(section_element)
            current_y += section_height + section.get('styling', {}).get('margin', 30)
        
        # Add visual elements
        visual_elements = styled_content.get('visual_elements', [])
        for element in visual_elements:
            if element.get('placement') == 'body':
                visual_element = self._create_visual_element(element, content_x, current_y, content_width)
                elements.append(visual_element)
                current_y += visual_element.height + 20
        
        return elements
    
    def _create_horizontal_layout(self, styled_content: Dict, layout: Dict) -> List[LayoutElement]:
        """Create horizontal layout arrangement"""
        elements = []
        content_area = layout['content_area']
        
        # Title spans full width
        title = styled_content.get('title', {})
        current_y = content_area['y']
        
        if title.get('text'):
            title_element = LayoutElement(
                id='title',
                type='title',
                content=title['text'],
                x=content_area['x'],
                y=current_y,
                width=content_area['width'],
                height=self._calculate_text_height(title['text'], title.get('font', ('Arial', 32, 'bold')), content_area['width']),
                priority=10,
                styling=title
            )
            elements.append(title_element)
            current_y += title_element.height + title.get('margin', 40)
        
        # Split remaining sections into two columns
        sections = styled_content.get('sections', [])
        column_width = (content_area['width'] - 40) // 2  # 40px gap between columns
        
        left_column_y = current_y
        right_column_y = current_y
        
        for i, section in enumerate(sections):
            section_height = self._calculate_section_height(section, column_width)
            
            if i % 2 == 0:  # Left column
                x = content_area['x']
                y = left_column_y
                left_column_y += section_height + 30
            else:  # Right column
                x = content_area['x'] + column_width + 40
                y = right_column_y
                right_column_y += section_height + 30
            
            section_element = LayoutElement(
                id=f'section_{section.get("id", i)}',
                type='section',
                content=section.get('condensed_text', section.get('content', '')),
                x=x,
                y=y,
                width=column_width,
                height=section_height,
                priority=section.get('priority', 5),
                styling=section.get('styling', {})
            )
            elements.append(section_element)
        
        return elements
    
    def _create_grid_layout(self, styled_content: Dict, layout: Dict) -> List[LayoutElement]:
        """Create grid layout arrangement"""
        elements = []
        grid = layout['grid']
        content_area = layout['content_area']
        
        # Title at top
        title = styled_content.get('title', {})
        current_y = content_area['y']
        
        if title.get('text'):
            title_element = LayoutElement(
                id='title',
                type='title',
                content=title['text'],
                x=content_area['x'],
                y=current_y,
                width=content_area['width'],
                height=80,
                priority=10,
                styling=title
            )
            elements.append(title_element)
            current_y += 120
        
        # Arrange sections in grid
        sections = styled_content.get('sections', [])
        grid_start_y = current_y
        
        for i, section in enumerate(sections):
            row = i // grid.columns
            col = i % grid.columns
            
            x = content_area['x'] + col * (grid.cell_width + grid.gap)
            y = grid_start_y + row * (grid.cell_height + grid.gap)
            
            section_element = LayoutElement(
                id=f'section_{section.get("id", i)}',
                type='section',
                content=section.get('condensed_text', section.get('content', '')),
                x=x,
                y=y,
                width=grid.cell_width,
                height=grid.cell_height,
                priority=section.get('priority', 5),
                styling=section.get('styling', {})
            )
            elements.append(section_element)
        
        return elements
    
    def _create_flow_layout(self, styled_content: Dict, layout: Dict) -> List[LayoutElement]:
        """Create flowing layout arrangement"""
        elements = []
        content_area = layout['content_area']
        
        # Title
        title = styled_content.get('title', {})
        current_y = content_area['y']
        
        if title.get('text'):
            title_element = LayoutElement(
                id='title',
                type='title',
                content=title['text'],
                x=content_area['x'],
                y=current_y,
                width=content_area['width'],
                height=80,
                priority=10,
                styling=title
            )
            elements.append(title_element)
            current_y += 100
        
        # Flow sections dynamically
        sections = styled_content.get('sections', [])
        current_x = content_area['x']
        row_height = 0
        max_width = content_area['width']
        
        for i, section in enumerate(sections):
            section_width = min(400, max_width // 2)  # Adaptive width
            section_height = self._calculate_section_height(section, section_width)
            
            # Check if we need to wrap to next row
            if current_x + section_width > content_area['x'] + max_width:
                current_x = content_area['x']
                current_y += row_height + 30
                row_height = 0
            
            section_element = LayoutElement(
                id=f'section_{section.get("id", i)}',
                type='section',
                content=section.get('condensed_text', section.get('content', '')),
                x=current_x,
                y=current_y,
                width=section_width,
                height=section_height,
                priority=section.get('priority', 5),
                styling=section.get('styling', {})
            )
            elements.append(section_element)
            
            current_x += section_width + 20
            row_height = max(row_height, section_height)
        
        return elements
    
    def _calculate_text_height(self, text: str, font: Tuple[str, int, str], width: int) -> int:
        """Calculate approximate text height"""
        if not text:
            return 0
        
        font_size = font[1] if len(font) > 1 else 16
        chars_per_line = width // (font_size * 0.6)  # Rough approximation
        lines = max(1, len(text) / chars_per_line)
        line_height = font_size * 1.4  # Standard line height
        
        return int(lines * line_height)
    
    def _calculate_section_height(self, section: Dict, width: int) -> int:
        """Calculate section height based on content"""
        content = section.get('condensed_text', section.get('content', ''))
        styling = section.get('styling', {})
        font = styling.get('font', ('Arial', 16, 'normal'))
        
        base_height = self._calculate_text_height(content, font, width)
        padding = styling.get('padding', 20)
        
        return base_height + padding * 2
    
    def _create_visual_element(self, element: Dict, x: int, y: int, max_width: int) -> LayoutElement:
        """Create visual element layout"""
        element_type = element.get('type', 'icon')
        importance = element.get('importance', 5)
        
        # Size based on importance
        if element_type == 'chart':
            width = min(max_width, 300)
            height = 200
        elif element_type == 'icon':
            size = 32 + (importance * 4)
            width = height = size
        else:
            width = min(max_width, 250)
            height = 150
        
        return LayoutElement(
            id=f'visual_{element.get("type", "element")}_{id(element)}',
            type=element_type,
            content=element.get('description', ''),
            x=x,
            y=y,
            width=width,
            height=height,
            priority=importance,
            styling=element.get('styling', {})
        )
    
    def optimize_layout(self, layout: Dict) -> Dict:
        """Optimize layout for better visual balance"""
        elements = layout.get('elements', [])
        
        # Remove overlapping elements
        elements = self._resolve_overlaps(elements)
        
        # Balance visual weight
        elements = self._balance_visual_weight(elements, layout)
        
        # Ensure minimum spacing
        elements = self._enforce_minimum_spacing(elements)
        
        layout['elements'] = elements
        return layout
    
    def _resolve_overlaps(self, elements: List[LayoutElement]) -> List[LayoutElement]:
        """Resolve overlapping elements"""
        for i, elem1 in enumerate(elements):
            for j, elem2 in enumerate(elements[i+1:], i+1):
                if self._elements_overlap(elem1, elem2):
                    # Move the lower priority element
                    if elem1.priority < elem2.priority:
                        elem1.y = elem2.y + elem2.height + 20
                    else:
                        elem2.y = elem1.y + elem1.height + 20
        
        return elements
    
    def _elements_overlap(self, elem1: LayoutElement, elem2: LayoutElement) -> bool:
        """Check if two elements overlap"""
        return not (elem1.x + elem1.width <= elem2.x or 
                   elem2.x + elem2.width <= elem1.x or 
                   elem1.y + elem1.height <= elem2.y or 
                   elem2.y + elem2.height <= elem1.y)
    
    def _balance_visual_weight(self, elements: List[LayoutElement], layout: Dict) -> List[LayoutElement]:
        """Balance visual weight of elements"""
        # Sort by priority
        elements.sort(key=lambda x: x.priority, reverse=True)
        
        # Adjust positions for better balance
        canvas_center_x = layout['canvas_width'] // 2
        
        for element in elements:
            if element.type == 'title':
                # Center titles
                element.x = canvas_center_x - element.width // 2
        
        return elements
    
    def _enforce_minimum_spacing(self, elements: List[LayoutElement]) -> List[LayoutElement]:
        """Ensure minimum spacing between elements"""
        min_spacing = 15
        
        # Sort by y position
        elements.sort(key=lambda x: x.y)
        
        for i in range(len(elements) - 1):
            current = elements[i]
            next_elem = elements[i + 1]
            
            required_y = current.y + current.height + min_spacing
            if next_elem.y < required_y:
                next_elem.y = required_y
        
        return elements
    
    def get_layout_bounds(self, layout: Dict) -> Dict:
        """Get the bounds of the entire layout"""
        elements = layout.get('elements', [])
        
        if not elements:
            return {'x': 0, 'y': 0, 'width': 0, 'height': 0}
        
        min_x = min(elem.x for elem in elements)
        min_y = min(elem.y for elem in elements)
        max_x = max(elem.x + elem.width for elem in elements)
        max_y = max(elem.y + elem.height for elem in elements)
        
        return {
            'x': min_x,
            'y': min_y,
            'width': max_x - min_x,
            'height': max_y - min_y
        }
    
    def export_layout_data(self, layout: Dict) -> Dict:
        """Export layout data for image generation"""
        return {
            'canvas': {
                'width': layout['canvas_width'],
                'height': layout['canvas_height'],
                'background': '#ffffff'
            },
            'elements': [
                {
                    'id': elem.id,
                    'type': elem.type,
                    'content': elem.content,
                    'position': {'x': elem.x, 'y': elem.y},
                    'size': {'width': elem.width, 'height': elem.height},
                    'priority': elem.priority,
                    'styling': elem.styling
                }
                for elem in layout.get('elements', [])
            ],
            'bounds': self.get_layout_bounds(layout)
        }