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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
"""PowerPoint layout inspection and minimal Pandoc reference-doc creation."""

from __future__ import annotations

import html
import os
import re
import tempfile
import zipfile
from collections import Counter
from pathlib import Path
from typing import Any, Iterable

from pptx import Presentation


MAX_PPTX_BYTES = 200 * 1024 * 1024

PANDOC_LAYOUTS = [
    "Title Slide",
    "Title and Content",
    "Section Header",
    "Two Content",
    "Comparison",
    "Content with Caption",
    "Blank",
]
MAPPING_CHOICES = ["不修改", *PANDOC_LAYOUTS]

PLACEHOLDER_LABELS = {
    "object/content": "object/content",
    "title": "title",
    "ctrTitle": "ctrTitle",
    "subTitle": "subTitle",
    "body": "body",
    "date": "date",
    "footer": "footer",
    "slideNumber": "slideNumber",
    "picture": "picture",
}

_XML_TYPE_NORMALIZATION = {
    "obj": "object/content",
    "dt": "date",
    "ftr": "footer",
    "sldNum": "slideNumber",
    "pic": "picture",
}

# severity=error produces FAIL and blocks creation; warning does not.
PANDOC_LAYOUT_CONTRACTS = {
    "Title Slide": [
        {
            "types": ("ctrTitle",),
            "min": 1,
            "label": "Center Title Holder",
            "severity": "error",
            "why": "Pandoc 封面標題需要 Center Title / ctrTitle。",
        },
        {
            "types": ("subTitle",),
            "min": 1,
            "label": "Subtitle Holder",
            "severity": "warning",
            "why": "沒有 Subtitle 時,subtitle 或 author metadata 可能無法輸出。",
        },
        {
            "types": ("date",),
            "min": 1,
            "label": "Date Holder",
            "severity": "warning",
            "why": "沒有 Date 時,date metadata 可能無法輸出。",
        },
    ],
    "Section Header": [
        {
            "types": ("title", "ctrTitle"),
            "min": 1,
            "label": "Title / Center Title Holder",
            "severity": "error",
            "why": "Section Header 至少需要 Title 或 Center Title。",
        },
    ],
    "Title and Content": [
        {
            "types": ("title", "ctrTitle"),
            "min": 1,
            "label": "Title Holder",
            "severity": "warning",
            "why": "主要內容仍可放置,但投影片標題可能無法正常輸出。",
        },
        {
            "types": ("object/content",),
            "min": 1,
            "label": "Content Holder",
            "severity": "error",
            "why": "一般內容需要至少 1 個沒有 type 屬性的 <p:ph>。",
        },
    ],
    "Two Content": [
        {
            "types": ("title", "ctrTitle"),
            "min": 1,
            "label": "Title Holder",
            "severity": "warning",
            "why": "主要內容仍可放置,但投影片標題可能無法正常輸出。",
        },
        {
            "types": ("object/content",),
            "min": 2,
            "label": "Content Holder",
            "severity": "error",
            "why": "Pandoc 會分別使用第 1、2 個 Content Holder 建立左右雙欄。",
        },
    ],
    "Comparison": [
        {
            "types": ("title", "ctrTitle"),
            "min": 1,
            "label": "Title Holder",
            "severity": "warning",
            "why": "比較內容仍可放置,但投影片標題可能無法正常輸出。",
        },
        {
            "types": ("body",),
            "min": 2,
            "label": "Body / Text Holder",
            "severity": "error",
            "why": "Comparison 需要左右各 1 個 Body / Text Holder。",
        },
        {
            "types": ("object/content",),
            "min": 2,
            "label": "Content Holder",
            "severity": "error",
            "why": "Comparison 需要左右各 1 個 Content Holder。",
        },
    ],
    "Content with Caption": [
        {
            "types": ("title", "ctrTitle"),
            "min": 1,
            "label": "Title Holder",
            "severity": "warning",
            "why": "主要內容仍可放置,但投影片標題可能無法正常輸出。",
        },
        {
            "types": ("body",),
            "min": 1,
            "label": "Body / Text Holder",
            "severity": "error",
            "why": "Content with Caption 需要至少 1 個 caption 文字區。",
        },
        {
            "types": ("object/content",),
            "min": 1,
            "label": "Content Holder",
            "severity": "error",
            "why": "Content with Caption 需要至少 1 個主要內容區。",
        },
    ],
    "Blank": [],
}


class TemplateError(ValueError):
    """Friendly, expected error raised while processing a user PPTX."""


def uploaded_file_path(file_value: Any) -> str:
    if file_value is None:
        raise TemplateError("尚未上傳 PowerPoint 模板。")
    return file_value if isinstance(file_value, str) else file_value.name


def validate_pptx(path: str) -> None:
    if not path or not path.lower().endswith(".pptx"):
        raise TemplateError("檔案格式必須是 .pptx。")
    if not os.path.isfile(path):
        raise TemplateError("找不到上傳的 PowerPoint 檔案,請重新上傳。")
    if os.path.getsize(path) > MAX_PPTX_BYTES:
        raise TemplateError("PowerPoint 模板不可超過 200 MB。")
    if not zipfile.is_zipfile(path):
        raise TemplateError("這個檔案不是有效的 PPTX / Open XML 壓縮檔。")


def _placeholder_xml(shape: Any):
    """Return the OOXML p:ph node without relying on the UI shape name."""
    try:
        nodes = shape._element.xpath(".//p:ph")
        return nodes[0] if nodes else None
    except Exception:
        return None


def _normalized_placeholder_type(ph_node: Any) -> str:
    xml_type = ph_node.get("type")
    if not xml_type:
        return "object/content"
    return _XML_TYPE_NORMALIZATION.get(xml_type, xml_type)


def placeholder_item(shape: Any) -> dict[str, Any]:
    ph_node = _placeholder_xml(shape)
    if ph_node is None:
        return {
            "name": getattr(shape, "name", "") or "",
            "type": "unknown",
            "idx": None,
        }

    raw_idx = ph_node.get("idx")
    try:
        idx = int(raw_idx) if raw_idx is not None else None
    except ValueError:
        idx = raw_idx
    return {
        # Kept for diagnostics only; classification is based exclusively on p:ph.
        "name": getattr(shape, "name", "") or "",
        "type": _normalized_placeholder_type(ph_node),
        "idx": idx,
    }


def placeholder_summary(placeholders: Iterable[dict[str, Any]]) -> str:
    counts = Counter(item.get("type", "unknown") for item in placeholders)
    if not counts:
        return "無 placeholder"
    preferred = [
        "ctrTitle", "title", "subTitle", "body", "object/content",
        "picture", "date", "footer", "slideNumber",
    ]
    result = []
    for placeholder_type in preferred:
        count = counts.pop(placeholder_type, 0)
        if count:
            label = PLACEHOLDER_LABELS.get(placeholder_type, placeholder_type)
            result.append(f"{label} × {count}" if count > 1 else label)
    for placeholder_type in sorted(counts):
        count = counts[placeholder_type]
        result.append(f"{placeholder_type} × {count}" if count > 1 else placeholder_type)
    return ", ".join(result)


def collect_layouts(prs: Presentation) -> list[dict[str, Any]]:
    """Collect every layout in stable Slide Master / Slide Layout order."""
    layouts: list[dict[str, Any]] = []
    sequence = 0
    for master_index, master in enumerate(prs.slide_masters):
        master_name = getattr(master, "name", "") or f"Master {master_index + 1}"
        for layout_index, layout in enumerate(master.slide_layouts):
            placeholders = [placeholder_item(shape) for shape in layout.placeholders]
            layouts.append(
                {
                    "sequence": sequence,
                    "master_index": master_index,
                    "master_name": master_name,
                    "layout_index": layout_index,
                    "name": layout.name or "",
                    "placeholders": placeholders,
                    "placeholder_summary": placeholder_summary(placeholders),
                }
            )
            sequence += 1
    return layouts


def analyze_pptx(path: str) -> dict[str, Any]:
    validate_pptx(path)
    try:
        presentation = Presentation(path)
        layouts = collect_layouts(presentation)
    except TemplateError:
        raise
    except Exception as error:
        raise TemplateError("無法解析 PPTX;檔案可能損壞或不是有效的 PowerPoint 簡報。") from error
    if not layouts:
        raise TemplateError("PPTX 中沒有找到任何 Slide Layout。")
    return {
        "source_path": path,
        "source_name": os.path.basename(path),
        "layouts": layouts,
    }


def sequential_mapping(layouts: Iterable[dict[str, Any]]) -> list[str]:
    return [
        PANDOC_LAYOUTS[index] if index < len(PANDOC_LAYOUTS) else "不修改"
        for index, _ in enumerate(layouts)
    ]


def final_layout_names(layouts, mapping_values) -> list[str]:
    names = []
    for index, layout in enumerate(layouts):
        selected = mapping_values[index] if index < len(mapping_values) else "不修改"
        names.append(selected if selected and selected != "不修改" else layout["name"])
    return names


def mapping_report(layouts, mapping_values) -> dict[str, Any]:
    selected_count = sum(value not in (None, "", "不修改") for value in mapping_values)
    final_names = final_layout_names(layouts, mapping_values)
    missing = [name for name in PANDOC_LAYOUTS if name not in final_names]
    duplicates = [name for name in PANDOC_LAYOUTS if final_names.count(name) > 1]
    changed = sum(
        index < len(mapping_values)
        and mapping_values[index] not in (None, "", "不修改", layout["name"])
        for index, layout in enumerate(layouts)
    )

    lines = [f"目前會修改 {changed} 個 Layout。"]
    if selected_count == 0:
        lines.append("尚未選擇任何 Mapping;請選擇至少一個 Pandoc Layout。")
    if missing:
        lines.append("缺少 Pandoc 標準名稱:" + "、".join(missing) + "。")
    else:
        lines.append("7 個 Pandoc 標準 Layout 名稱都已存在。")
    if duplicates:
        lines.append(
            "WARNING:以下 Pandoc 名稱出現超過一次:"
            + "、".join(duplicates)
            + "。Pandoc 可能只匹配第一個,不建議重複設定。"
        )
    return {
        "text": "\n".join(lines),
        "selected_count": selected_count,
        "missing": missing,
        "duplicates": duplicates,
        "changed": changed,
        "names_ok": not missing,
    }


def validate_layout_contract(layout: dict[str, Any], target_name: str) -> dict[str, Any]:
    placeholders = layout.get("placeholders", [])
    rules = PANDOC_LAYOUT_CONTRACTS.get(target_name)
    if rules is None:
        return {
            "status": "SKIP",
            "checks": [],
            "errors": [],
            "warnings": [],
            "found": placeholder_summary(placeholders),
        }

    checks = []
    errors = []
    warnings = []
    for rule in rules:
        count = sum(
            item.get("type") in rule["types"] for item in placeholders
        )
        passed = count >= rule["min"]
        checks.append({**rule, "count": count, "passed": passed})
        if not passed:
            message = (
                f"缺少 {rule['label']}(需要 {rule['min']} 個,目前 {count} 個)。"
                f"{rule['why']}"
            )
            (errors if rule["severity"] == "error" else warnings).append(message)

    explicit_idxs = [item["idx"] for item in placeholders if item.get("idx") is not None]
    duplicate_idxs = sorted(
        (idx for idx, count in Counter(explicit_idxs).items() if count > 1),
        key=str,
    )
    if duplicate_idxs:
        warnings.append(
            "Placeholder idx 重複:"
            + "、".join(map(str, duplicate_idxs))
            + "。工具不會自動修改 idx;請在 PowerPoint 母片檢視中確認。"
        )

    status = "FAIL" if errors else ("WARNING" if warnings else "PASS")
    return {
        "status": status,
        "checks": checks,
        "errors": errors,
        "warnings": warnings,
        "found": placeholder_summary(placeholders),
    }


def validate_mapped_layouts(layouts, mapping_values) -> list[dict[str, Any]]:
    results = []
    final_names = final_layout_names(layouts, mapping_values)
    for index, layout in enumerate(layouts):
        target = final_names[index]
        if target in PANDOC_LAYOUT_CONTRACTS:
            results.append(
                {
                    "index": index,
                    "target": target,
                    "layout": layout,
                    "result": validate_layout_contract(layout, target),
                }
            )
    return results


def row_statuses(layouts, mapping_values) -> list[str]:
    final_names = final_layout_names(layouts, mapping_values)
    statuses = []
    for index, layout in enumerate(layouts):
        target = final_names[index]
        if target not in PANDOC_LAYOUT_CONTRACTS:
            statuses.append("不檢查")
        else:
            statuses.append(validate_layout_contract(layout, target)["status"])
    return statuses


def structure_report_html(layouts, mapping_values) -> tuple[str, bool, bool]:
    validated = validate_mapped_layouts(layouts, mapping_values)
    if not validated:
        return (
            '<div class="contract-empty"><span>PANDOC PLACEHOLDER CONTRACT</span>'
            '<strong>沒有可檢查的 Pandoc Layout</strong>'
            '<p>請先把至少一個 Layout 對應到 Pandoc 標準名稱。</p></div>',
            False,
            False,
        )

    rows = []
    has_fail = False
    has_warning = False
    for item in validated:
        result = item["result"]
        has_fail |= result["status"] == "FAIL"
        has_warning |= result["status"] == "WARNING"
        badge_class = {
            "PASS": "contract-pass",
            "WARNING": "contract-warning",
            "FAIL": "contract-fail",
        }[result["status"]]
        checks = []
        for check in result["checks"]:
            icon = "✓" if check["passed"] else ("✕" if check["severity"] == "error" else "!")
            check_class = "ok" if check["passed"] else ("bad" if check["severity"] == "error" else "warn")
            checks.append(
                f'<span class="contract-check {check_class}">{icon} '
                f'{html.escape(check["label"])} {check["count"]} / {check["min"]}</span>'
            )
        if not checks:
            checks.append('<span class="contract-check ok">✓ 不要求內容 Placeholder</span>')
        messages = result["errors"] + result["warnings"]
        messages_html = ""
        if messages:
            messages_html = '<ul class="contract-messages">' + "".join(
                f"<li>{html.escape(message)}</li>" for message in messages
            ) + "</ul>"
        layout = item["layout"]
        rows.append(
            f'''<div class="contract-row">
                <div class="contract-layout"><span class="contract-index">{item["index"] + 1:02d}</span>
                <div><strong>{html.escape(item["target"])}</strong>
                <small>Master {layout["master_index"] + 1} · {html.escape(layout["name"] or "(未命名)")}</small></div></div>
                <div class="contract-found">{html.escape(result["found"])}</div>
                <div><span class="contract-badge {badge_class}">{result["status"]}</span>
                <div class="contract-checks">{"".join(checks)}</div>{messages_html}</div>
            </div>'''
        )

    if has_fail:
        summary_class = "summary-fail"
        summary_text = "必要 Placeholder 不足;修正後才能建立 reference PPTX。"
    elif has_warning:
        summary_class = "summary-warning"
        summary_text = "主要結構可用,但有不阻止輸出的注意事項。"
    else:
        summary_class = "summary-pass"
        summary_text = "所有已對應 Layout 的 Placeholder contract 均通過。"

    report = f'''<div class="contract-report">
        <div class="contract-summary {summary_class}">
            <div><span>PANDOC PLACEHOLDER CONTRACT</span><strong>{summary_text}</strong></div>
            <small>共檢查 {len(validated)} 個 Pandoc Layout</small>
        </div>
        <div class="contract-head"><span>Layout</span><span>實際 Placeholder</span><span>檢查結果</span></div>
        {"".join(rows)}
        <div class="contract-footnote"><strong>Content Holder 判斷:</strong>
        直接讀取 OOXML <code>&lt;p:ph&gt;</code>;沒有 <code>type</code> attribute
        才視為 Pandoc 使用的 <code>object/content</code>,不依 PowerPoint shape name 判斷。</div>
    </div>'''
    return report, not has_fail, has_warning


def iter_layout_objects(prs: Presentation):
    for master_index, master in enumerate(prs.slide_masters):
        for layout_index, layout in enumerate(master.slide_layouts):
            yield master_index, layout_index, layout


def create_reference_pptx(
    source_path: str,
    layouts: list[dict[str, Any]],
    mapping_values: list[str],
) -> str:
    """Rename selected layouts and save a unique new file; never overwrite source."""
    validate_pptx(source_path)
    if not any(value not in (None, "", "不修改") for value in mapping_values):
        raise TemplateError("沒有選擇任何 Mapping;請至少指定一個 Pandoc Layout。")

    try:
        presentation = Presentation(source_path)
        lookup = {
            (item["master_index"], item["layout_index"]): index
            for index, item in enumerate(layouts)
        }
        for master_index, layout_index, layout in iter_layout_objects(presentation):
            row_index = lookup.get((master_index, layout_index))
            if row_index is None or row_index >= len(mapping_values):
                continue
            target_name = mapping_values[row_index]
            if target_name and target_name != "不修改":
                if target_name not in PANDOC_LAYOUTS:
                    raise TemplateError(f"不支援的 Pandoc Layout 名稱:{target_name}")
                layout.name = target_name

        safe_stem = re.sub(r"[^A-Za-z0-9._-]+", "-", Path(source_path).stem).strip("-._")
        safe_stem = safe_stem or "template"
        output_dir = tempfile.mkdtemp(prefix="pandoc-reference-", dir="/tmp")
        output_path = os.path.join(output_dir, f"{safe_stem}-pandoc-reference.pptx")
        if os.path.realpath(output_path) == os.path.realpath(source_path):
            raise TemplateError("安全檢查失敗:輸出路徑不可與原始 PPTX 相同。")
        presentation.save(output_path)
        Presentation(output_path)
        return output_path
    except TemplateError:
        raise
    except Exception as error:
        raise TemplateError("輸出檔案建立失敗,請確認 PPTX 未損壞後再試一次。") from error