# -*- coding: utf-8 -*-
"""Overflow + collision rough check for the deck."""
from pptx import Presentation
from pptx.util import Emu

PATH = r"C:\laragon\www\worker-system\ai-image-ppt\AI文字生圖入門教學.pptx"
prs = Presentation(PATH)
SW = prs.slide_width / 914400
SH = prs.slide_height / 914400

def char_w(ch, size):
    # CJK fullwidth ~ 1.0em, latin ~0.55em
    o = ord(ch)
    if o < 128:
        return size * 0.55 / 72
    return size * 1.02 / 72

issues = []
for si, slide in enumerate(prs.slides, 1):
    boxes = []
    for sh in slide.shapes:
        if not sh.has_text_frame:
            continue
        txt = sh.text_frame.text
        if not txt.strip():
            continue
        x, y = sh.left / 914400, sh.top / 914400
        w, h = sh.width / 914400, sh.height / 914400
        # estimate needed height
        total_h = 0
        for p in sh.text_frame.paragraphs:
            runs = [(r.text, (r.font.size.pt if r.font.size else 14)) for r in p.runs]
            if not runs:
                continue
            maxsz = max(s for _, s in runs)
            line_w = sum(char_w(c, s) for t, s in runs for c in t)
            avail = max(w - 0.12, 0.3)
            import math
            lines = max(1, math.ceil(line_w / avail))
            ls = p.line_spacing if p.line_spacing else 1.12
            total_h += lines * maxsz * ls / 72
            total_h += ((p.space_before.pt if p.space_before else 0) + (p.space_after.pt if p.space_after else 0)) / 72
        if total_h > h + 0.12:
            issues.append(f"S{si} OVERFLOW est {total_h:.2f}in > box {h:.2f}in | {txt[:28]!r}")
        if x < -0.05 or y < -0.05 or x + w > SW + 0.05 or y + h > SH + 0.05:
            issues.append(f"S{si} OUTSIDE slide ({x:.2f},{y:.2f},{w:.2f},{h:.2f}) | {txt[:28]!r}")
        boxes.append((x, y, w, h, txt[:20]))
    for i in range(len(boxes)):
        for j in range(i + 1, len(boxes)):
            a, b = boxes[i], boxes[j]
            ox = min(a[0]+a[2], b[0]+b[2]) - max(a[0], b[0])
            oy = min(a[1]+a[3], b[1]+b[3]) - max(a[1], b[1])
            if ox > 0.15 and oy > 0.15:
                issues.append(f"S{si} OVERLAP {a[4]!r} x {b[4]!r} ({ox:.2f}x{oy:.2f})")

print(f"slides: {len(prs.slides._sldIdLst)}")
if issues:
    for it in issues:
        print("!!", it)
else:
    print("no issues found")
