#!/usr/bin/env python3
"""Import Game Show Questions.pptx → quizzes/<id>.json for tss-poll / pave-poll.

Correct-answer convention (TSS Episode 22 host deck):
  Primary: the correct choice shape has a solidFill schemeClr of accent6
           (wrong choices use accent2 only).
  Fallback: speaker notes begin with True./False. or A./B./C./D. matching a choice.
  Ambiguity: if accent6 is missing and notes don't parse, correct defaults to 0
             and the question is flagged in stderr / quiz.importWarnings.

Usage:
  python3 scripts/import-pptx.py fixtures/Game\\ Show\\ Questions.pptx \\
      -o quizzes/tss-ep22.json --id tss-ep22 --title "The Schiff Show Episode #22" \\
      --brand theschiffshow
"""
from __future__ import annotations
import argparse, json, re, sys
from pathlib import Path
from zipfile import ZipFile
from lxml import etree
from pptx import Presentation

NS = {
    "a": "http://schemas.openxmlformats.org/drawingml/2006/main",
    "p": "http://schemas.openxmlformats.org/presentationml/2006/main",
    "r": "http://schemas.openxmlformats.org/officeDocument/2006/relationships",
}
CHOICE_RE = re.compile(r"^([A-Da-d])\.\s*(.+)$", re.DOTALL)
NOTES_LETTER_RE = re.compile(r"^\s*([A-Da-d])\b")
NOTES_TF_RE = re.compile(r"^\s*(True|False)\b", re.I)
Q_TITLE_RE = re.compile(r"question\s*(\d+)", re.I)


def strip_letter(text: str) -> tuple[str | None, str]:
    m = CHOICE_RE.match(text.strip())
    if m:
        return m.group(1).upper(), m.group(2).strip()
    return None, text.strip()


def has_accent6(shape_el) -> bool:
    vals = shape_el.xpath(".//a:solidFill/a:schemeClr/@val", namespaces=NS)
    return "accent6" in vals


def parse_slide_xml_choices(slide_xml: bytes) -> list[dict]:
    """Return choice shapes in document order with accent6 flag."""
    root = etree.fromstring(slide_xml)
    out = []
    for sp in root.xpath(".//p:sp", namespaces=NS):
        texts = "".join(t.text or "" for t in sp.xpath(".//a:t", namespaces=NS)).strip()
        if not texts:
            continue
        letter, body = strip_letter(texts)
        if letter is None and not re.match(r"^(True|False)\b", texts, re.I):
            # not a lettered choice; skip titles/questions/banners
            continue
        # True/False without letter still count if short
        if letter is None:
            # only accept bare True/False as choices
            if not re.fullmatch(r"(True|False)\s*", texts, re.I):
                continue
            letter = "A" if texts.strip().lower().startswith("t") else "B"
            body = texts.strip()
        out.append({
            "letter": letter,
            "raw": texts,
            "text": body,
            "accent6": has_accent6(sp),
        })
    return out


def notes_correct_index(notes: str, choices: list[dict]) -> int | None:
    if not notes:
        return None
    first = notes.strip().splitlines()[0].strip()
    m = NOTES_LETTER_RE.match(first)
    if m:
        want = m.group(1).upper()
        for i, c in enumerate(choices):
            if c["letter"] == want:
                return i
    m = NOTES_TF_RE.match(first)
    if m:
        want = m.group(1).lower()
        for i, c in enumerate(choices):
            if c["text"].lower().startswith(want):
                return i
        # also match against raw
        for i, c in enumerate(choices):
            if want in c["raw"].lower():
                return i
    # substring match of first ~40 chars of a choice in notes
    for i, c in enumerate(choices):
        key = c["text"][:40]
        if key and key.lower() in notes.lower():
            return i
    return None


def extract_question_text(slide) -> str:
    """Largest non-choice, non-title body text on the slide."""
    candidates = []
    for shape in slide.shapes:
        if not shape.has_text_frame:
            continue
        t = shape.text_frame.text.strip()
        if not t or Q_TITLE_RE.fullmatch(t.replace("\n", " ").strip()):
            continue
        if CHOICE_RE.match(t) or re.fullmatch(r"(True|False)\s*", t, re.I):
            continue
        if t.lower().startswith("(repeat question"):
            continue
        # prefer longer question bodies
        area = getattr(shape, "width", 0) * getattr(shape, "height", 0)
        candidates.append((len(t), area, t))
    if not candidates:
        return ""
    candidates.sort(reverse=True)
    return re.sub(r"\s+", " ", candidates[0][2]).strip()


def extract_meta(prs: Presentation) -> tuple[str, str]:
    title, subtitle = "Imported Quiz", ""
    if prs.slides:
        s0 = prs.slides[0]
        texts = [sh.text_frame.text.strip() for sh in s0.shapes if sh.has_text_frame and sh.text_frame.text.strip()]
        if texts:
            title = texts[0].splitlines()[0]
        if len(texts) > 1:
            subtitle = " ".join(texts[1].splitlines())
    return title, subtitle


def import_pptx(path: Path, quiz_id: str, title: str | None, brand: str, default_time: int) -> dict:
    prs = Presentation(str(path))
    cover_title, cover_sub = extract_meta(prs)
    warnings = []
    questions = []

    # map slide index → slideN.xml part for accent6 detection
    with ZipFile(path) as z:
        rels = etree.fromstring(z.read("ppt/_rels/presentation.xml.rels"))
        rid_to_target = {
            rel.get("Id"): rel.get("Target")
            for rel in rels
        }
        pres = etree.fromstring(z.read("ppt/presentation.xml"))
        sld_ids = [
            (el.get("{http://schemas.openxmlformats.org/officeDocument/2006/relationships}id"),)
            for el in pres.xpath("//p:sldIdLst/p:sldId", namespaces=NS)
        ]
        slide_xmls = []
        for (rid,) in sld_ids:
            target = rid_to_target[rid].lstrip("/")
            if not target.startswith("ppt/"):
                target = "ppt/" + target
            slide_xmls.append(z.read(target))

    for i, slide in enumerate(prs.slides):
        if i == 0 and not any(
            CHOICE_RE.match(sh.text_frame.text.strip())
            for sh in slide.shapes if sh.has_text_frame and sh.text_frame.text.strip()
        ):
            continue  # title slide
        notes = ""
        if slide.has_notes_slide:
            notes = slide.notes_slide.notes_text_frame.text.strip()
        choices_meta = parse_slide_xml_choices(slide_xmls[i])
        if len(choices_meta) < 2:
            warnings.append(f"slide {i+1}: fewer than 2 choices, skipped")
            continue
        # sort by letter A,B,C,D if all lettered
        if all(c["letter"] for c in choices_meta):
            choices_meta.sort(key=lambda c: c["letter"])
        qtext = extract_question_text(slide)
        if not qtext:
            warnings.append(f"slide {i+1}: no question text found")
            continue
        accent_idxs = [j for j, c in enumerate(choices_meta) if c["accent6"]]
        correct = None
        source = None
        if len(accent_idxs) == 1:
            correct = accent_idxs[0]
            source = "accent6"
        elif len(accent_idxs) > 1:
            warnings.append(f"slide {i+1}: multiple accent6 choices {accent_idxs}; using notes fallback")
        if correct is None:
            correct = notes_correct_index(notes, choices_meta)
            source = "notes" if correct is not None else None
        if correct is None:
            correct = 0
            source = "default0"
            warnings.append(f"slide {i+1}: could not detect correct answer; defaulted to index 0")
        # For T/F store bare True/False; for MC keep full option text (without forcing letter)
        choice_texts = []
        for c in choices_meta:
            if c["text"].lower() in ("true", "false") and len(choices_meta) == 2:
                choice_texts.append(c["text"][:1].upper() + c["text"][1:].lower() if c["text"].lower() in ("true", "false") else c["text"])
                # normalize True/False capitalization
                choice_texts[-1] = "True" if c["text"].lower().startswith("t") else "False"
            else:
                # keep letter prefix for Slido-compatible MC labels
                choice_texts.append(f"{c['letter']}. {c['text']}")
        explanation = notes.replace("\n", " ").strip() if notes else ""
        # trim explanation if it starts with the answer letter/word — keep full notes as explanation
        questions.append({
            "text": qtext,
            "choices": choice_texts,
            "correct": correct,
            "timeLimit": default_time,
            "explanation": explanation,
            "_import": {"slide": i + 1, "correctSource": source, "letters": [c["letter"] for c in choices_meta]},
        })

    quiz = {
        "id": quiz_id,
        "title": title or (cover_sub and f"The Schiff Show – {cover_sub}") or cover_title,
        "brand": brand,
        "defaultTimeLimit": default_time,
        "source": str(path.name),
        "importNotes": (
            "Correct answers marked in the PPTX by accent6 fill on the choice shape; "
            "speaker notes used as fallback and as explanation text."
        ),
        "questions": [{k: v for k, v in q.items() if not k.startswith("_")} for q in questions],
    }
    # attach warnings separately for tooling
    quiz["_warnings"] = warnings
    quiz["_debug"] = [{"text": q["text"][:60], **q["_import"]} for q in questions]
    return quiz


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("pptx", type=Path)
    ap.add_argument("-o", "--output", type=Path, required=True)
    ap.add_argument("--id", default="tss-imported")
    ap.add_argument("--title", default=None)
    ap.add_argument("--brand", default="theschiffshow")
    ap.add_argument("--time-limit", type=int, default=20)
    args = ap.parse_args()
    quiz = import_pptx(args.pptx, args.id, args.title, args.brand, args.time_limit)
    warnings = quiz.pop("_warnings", [])
    debug = quiz.pop("_debug", [])
    args.output.parent.mkdir(parents=True, exist_ok=True)
    args.output.write_text(json.dumps(quiz, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
    print(f"Wrote {args.output} with {len(quiz['questions'])} questions", file=sys.stderr)
    for d in debug:
        print(f"  Q slide {d['slide']}: correct={d.get('correctSource')} letters={d['letters']} :: {d['text']}", file=sys.stderr)
    for w in warnings:
        print(f"WARNING: {w}", file=sys.stderr)
    if warnings:
        sys.exit(2)

if __name__ == "__main__":
    main()
