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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
from os import PathLike
from pathlib import Path
from typing import Any, Dict, Optional

from pptx.util import Inches

from ..utils.pptx_functions import PptxEditor


_SHAPE_ID_UNSET = object()


def create_presentation(path: Optional[str | PathLike[str]] = None) -> PptxEditor:
    if path is None:
        return PptxEditor()
    return PptxEditor(str(path))


def save_presentation(editor: PptxEditor, path: str | PathLike[str]) -> Dict[str, Any]:
    output_path = Path(path)
    output_path.parent.mkdir(parents=True, exist_ok=True)
    editor.prs.save(output_path)
    return {
        "path": str(output_path.resolve()),
        "slide_count": len(editor.prs.slides),
    }


def register_theme(
    editor: PptxEditor, theme: Dict[str, Any], name: str = "default"
) -> str:
    return editor.register_theme(name, theme)


def update_theme(
    editor: PptxEditor, updates: Dict[str, Any], name: str = "default"
) -> None:
    editor.update_theme(name, updates)


def _remove_bindings(
    editor: PptxEditor,
    *,
    slide_id: Optional[int] = None,
    shape_id: Any = _SHAPE_ID_UNSET,
    apply_method: Optional[str] = None,
    theme_name: Optional[str] = None,
) -> None:
    theme_names = (
        [theme_name] if theme_name is not None else list(editor._theme_bindings)
    )

    for current_theme_name in theme_names:
        remaining = []
        for binding in editor._theme_bindings.get(current_theme_name, []):
            if slide_id is not None and binding.slide_id != slide_id:
                remaining.append(binding)
                continue
            if shape_id is not _SHAPE_ID_UNSET and binding.shape_id != shape_id:
                remaining.append(binding)
                continue
            if apply_method is not None and binding.apply_method != apply_method:
                remaining.append(binding)
                continue
        editor._theme_bindings[current_theme_name] = remaining


def _get_required(spec: Dict[str, Any], key: str) -> Any:
    if key not in spec:
        raise ValueError(f"Shape spec missing required field '{key}'")
    return spec[key]


def _get_optional_geometry(spec: Dict[str, Any]) -> Dict[str, float]:
    geometry = {}
    for source_key, target_key in (
        ("x", "left"),
        ("y", "top"),
        ("w", "width"),
        ("h", "height"),
    ):
        if source_key in spec:
            geometry[target_key] = spec[source_key]
    return geometry


def _apply_geometry_updates(
    editor: PptxEditor, slide_id: int, shape_id: int, spec: Dict[str, Any]
) -> None:
    geometry = _get_optional_geometry(spec)
    if not geometry:
        return

    shape = editor._get_shape_by_id(slide_id, shape_id)
    if "left" in geometry:
        shape.left = Inches(geometry["left"])
    if "top" in geometry:
        shape.top = Inches(geometry["top"])
    if "width" in geometry:
        shape.width = Inches(geometry["width"])
    if "height" in geometry:
        shape.height = Inches(geometry["height"])


def _record_named_shape(
    result: Dict[str, Any], spec: Dict[str, Any], shape_id: int
) -> None:
    name = spec.get("name")
    if name is None:
        return
    if name in result["named_shapes"]:
        raise ValueError(f"Duplicate shape name '{name}' in one tool call")
    result["named_shapes"][name] = shape_id


def _create_accent_bar(
    editor: PptxEditor, slide_id: int, spec: Dict[str, Any], theme_name: str
) -> int:
    return editor.add_accent_bar_by_id(
        slide_id,
        _get_required(spec, "color_hex"),
        height=spec.get("height", 0.35),
        theme_name=theme_name,
        bind_theme=True,
    )


def _create_text(
    editor: PptxEditor, slide_id: int, spec: Dict[str, Any], theme_name: str
) -> int:
    shape_id = editor.add_textbox_by_id(
        slide_id,
        _get_required(spec, "x"),
        _get_required(spec, "y"),
        _get_required(spec, "w"),
        _get_required(spec, "h"),
    )
    editor.insert_text_by_id(slide_id, shape_id, _get_required(spec, "text"))
    if spec.get("style"):
        editor.style_text_by_id(
            slide_id,
            shape_id,
            theme_name=theme_name,
            bind_theme=True,
            **spec["style"],
        )
    return shape_id


def _create_chart(
    editor: PptxEditor, slide_id: int, spec: Dict[str, Any], theme_name: str
) -> int:
    return editor.add_chart_by_id(
        slide_id,
        _get_required(spec, "chart_type"),
        _get_required(spec, "chart_data"),
        _get_required(spec, "x"),
        _get_required(spec, "y"),
        _get_required(spec, "w"),
        _get_required(spec, "h"),
        style=spec.get("style"),
        theme_name=theme_name,
        bind_theme=True,
    )


def _create_table(
    editor: PptxEditor, slide_id: int, spec: Dict[str, Any], theme_name: str
) -> int:
    table_data = _get_required(spec, "table_data")
    rows = len(table_data)
    cols = max((len(row) for row in table_data), default=0)
    if rows == 0 or cols == 0:
        raise ValueError("table_data must include at least one row and one column")

    return editor.add_table_by_id(
        slide_id,
        rows,
        cols,
        table_data,
        _get_required(spec, "x"),
        _get_required(spec, "y"),
        _get_required(spec, "w"),
        _get_required(spec, "h"),
        style=spec.get("style"),
        theme_name=theme_name,
        bind_theme=True,
    )


def _create_image(
    editor: PptxEditor, slide_id: int, spec: Dict[str, Any], theme_name: str
) -> int:
    del theme_name
    return editor.add_image_by_id(
        slide_id,
        _get_required(spec, "image_path"),
        _get_required(spec, "x"),
        _get_required(spec, "y"),
        cx=spec.get("w"),
        cy=spec.get("h"),
    )


def _update_text(
    editor: PptxEditor, slide_id: int, spec: Dict[str, Any], theme_name: str
) -> int:
    shape_id = _get_required(spec, "shape_id")
    _apply_geometry_updates(editor, slide_id, shape_id, spec)
    if "text" in spec:
        editor.insert_text_by_id(slide_id, shape_id, spec["text"])
    if "style" in spec:
        _remove_bindings(
            editor,
            slide_id=slide_id,
            shape_id=shape_id,
            apply_method="style_text_by_id",
        )
        editor.style_text_by_id(
            slide_id,
            shape_id,
            theme_name=theme_name,
            bind_theme=True,
            **spec["style"],
        )
    return shape_id


def _update_chart(
    editor: PptxEditor, slide_id: int, spec: Dict[str, Any], theme_name: str
) -> int:
    shape_id = _get_required(spec, "shape_id")
    _apply_geometry_updates(editor, slide_id, shape_id, spec)
    if "style" in spec:
        _remove_bindings(
            editor,
            slide_id=slide_id,
            shape_id=shape_id,
            apply_method="style_chart_by_id",
        )
        editor.style_chart_by_id(
            slide_id,
            shape_id,
            theme_name=theme_name,
            bind_theme=True,
            **spec["style"],
        )
    return shape_id


def _update_table(
    editor: PptxEditor, slide_id: int, spec: Dict[str, Any], theme_name: str
) -> int:
    shape_id = _get_required(spec, "shape_id")
    _apply_geometry_updates(editor, slide_id, shape_id, spec)
    if "style" in spec:
        _remove_bindings(
            editor,
            slide_id=slide_id,
            shape_id=shape_id,
            apply_method="style_table_by_id",
        )
        editor.style_table_by_id(
            slide_id,
            shape_id,
            theme_name=theme_name,
            bind_theme=True,
            **spec["style"],
        )
    return shape_id


def _update_accent_bar(
    editor: PptxEditor, slide_id: int, spec: Dict[str, Any], theme_name: str
) -> int:
    shape_id = _get_required(spec, "shape_id")
    _apply_geometry_updates(editor, slide_id, shape_id, spec)
    if "height" in spec:
        shape = editor._get_shape_by_id(slide_id, shape_id)
        shape.height = Inches(spec["height"])
    if "color_hex" in spec:
        _remove_bindings(
            editor,
            slide_id=slide_id,
            shape_id=shape_id,
            apply_method="style_shape_fill_by_id",
        )
        editor.style_shape_fill_by_id(
            slide_id,
            shape_id,
            fill_color_hex=spec["color_hex"],
            theme_name=theme_name,
            bind_theme=True,
        )
    return shape_id


def _update_image(
    editor: PptxEditor, slide_id: int, spec: Dict[str, Any], theme_name: str
) -> int:
    del theme_name
    shape_id = _get_required(spec, "shape_id")
    if "image_path" in spec:
        raise ValueError(
            "Updating image content is not supported; delete and re-add the image"
        )
    _apply_geometry_updates(editor, slide_id, shape_id, spec)
    return shape_id


_CREATE_DISPATCH = {
    "accent_bar": _create_accent_bar,
    "text": _create_text,
    "chart": _create_chart,
    "table": _create_table,
    "image": _create_image,
}

_UPDATE_DISPATCH = {
    "accent_bar": _update_accent_bar,
    "text": _update_text,
    "chart": _update_chart,
    "table": _update_table,
    "image": _update_image,
}


def _create_shape_from_spec(
    editor: PptxEditor, slide_id: int, spec: Dict[str, Any], theme_name: str
) -> int:
    shape_type = _get_required(spec, "type")
    if shape_type not in _CREATE_DISPATCH:
        raise ValueError(f"Unsupported shape type '{shape_type}'")
    return _CREATE_DISPATCH[shape_type](editor, slide_id, spec, theme_name)


def _update_shape_from_spec(
    editor: PptxEditor, slide_id: int, spec: Dict[str, Any], theme_name: str
) -> int:
    shape_type = _get_required(spec, "type")
    if shape_type not in _UPDATE_DISPATCH:
        raise ValueError(f"Unsupported shape type '{shape_type}'")
    return _UPDATE_DISPATCH[shape_type](editor, slide_id, spec, theme_name)


def _delete_shape(editor: PptxEditor, slide_id: int, shape_id: int) -> None:
    shape = editor._get_shape_by_id(slide_id, shape_id)
    shape._element.getparent().remove(shape._element)
    _remove_bindings(editor, slide_id=slide_id, shape_id=shape_id)


def delete_slide(editor: PptxEditor, slide_id: int) -> Dict[str, Any]:
    slide_index = editor.get_slide_index(slide_id)
    editor.delete_slide_by_id(slide_id)
    _remove_bindings(editor, slide_id=slide_id)
    return {
        "slide_id": slide_id,
        "deleted_slide_index": slide_index + 1,
        "remaining_slide_count": len(editor.prs.slides),
    }


def create_slide(
    editor: PptxEditor,
    *,
    theme_name: str = "default",
    background_color: Optional[str] = None,
    shapes: Optional[list[Dict[str, Any]]] = None,
) -> Dict[str, Any]:
    slide_index = editor.add_slide()
    slide_id = editor.get_slide_id(slide_index)
    result = {"slide_id": slide_id, "shape_ids": [], "named_shapes": {}}

    if background_color is not None:
        editor.set_slide_background_by_id(
            slide_id,
            background_color,
            theme_name=theme_name,
            bind_theme=True,
        )

    for spec in shapes or []:
        shape_id = _create_shape_from_spec(editor, slide_id, spec, theme_name)
        result["shape_ids"].append(shape_id)
        _record_named_shape(result, spec, shape_id)

    return result


def update_slide(
    editor: PptxEditor,
    slide_id: int,
    *,
    theme_name: str = "default",
    background_color: Optional[str] = None,
    delete_shape_ids: Optional[list[int]] = None,
    add_shapes: Optional[list[Dict[str, Any]]] = None,
    update_shapes: Optional[list[Dict[str, Any]]] = None,
) -> Dict[str, Any]:
    editor._get_slide_by_id(slide_id)
    delete_shape_ids = delete_shape_ids or []
    add_shapes = add_shapes or []
    update_shapes = update_shapes or []

    delete_set = set(delete_shape_ids)
    if len(delete_set) != len(delete_shape_ids):
        raise ValueError("delete_shape_ids contains duplicates")

    update_shape_ids = []
    for spec in update_shapes:
        shape_id = _get_required(spec, "shape_id")
        if shape_id in delete_set:
            raise ValueError(
                f"Shape id {shape_id} cannot be both updated and deleted in one call"
            )
        update_shape_ids.append(shape_id)

    if len(set(update_shape_ids)) != len(update_shape_ids):
        raise ValueError("update_shapes contains duplicate shape_id values")

    result = {
        "slide_id": slide_id,
        "deleted_shape_ids": [],
        "updated_shape_ids": [],
        "created_shape_ids": [],
        "named_shapes": {},
    }

    if background_color is not None:
        _remove_bindings(
            editor,
            slide_id=slide_id,
            shape_id=None,
            apply_method="set_slide_background_by_id",
        )
        editor.set_slide_background_by_id(
            slide_id,
            background_color,
            theme_name=theme_name,
            bind_theme=True,
        )

    for spec in update_shapes:
        shape_id = _update_shape_from_spec(editor, slide_id, spec, theme_name)
        result["updated_shape_ids"].append(shape_id)
        _record_named_shape(result, spec, shape_id)

    for spec in add_shapes:
        shape_id = _create_shape_from_spec(editor, slide_id, spec, theme_name)
        result["created_shape_ids"].append(shape_id)
        _record_named_shape(result, spec, shape_id)

    for shape_id in delete_shape_ids:
        _delete_shape(editor, slide_id, shape_id)
        result["deleted_shape_ids"].append(shape_id)

    return result


__all__ = [
    "create_presentation",
    "save_presentation",
    "register_theme",
    "update_theme",
    "create_slide",
    "delete_slide",
    "update_slide",
]