"""§6 综合 Lab · slide 82-92 (11 内容页) · v0.2 真实内容版

嵌入 1 张图（G4 8 高频踩坑）+ 10 张自画版面（准备清单 + 9 步 Lab 命令）
"""

from pathlib import Path
from pptx.util import Inches
from pptx.enum.text import PP_ALIGN

from build_main import (
    _fill_ph, _add_textbox, _add_card,
    NAVY, CORAL, CORAL_LIGHT, BLUE_ACCENT, GREEN, GOLD,
    GRAY_300, GRAY_500, GRAY_700, WHITE,
)
from build_sec_M1 import _add_centered_image, _title


def _cmd_box(slide, x, y, w, h, cmd, output=None):
    """终端命令样例 box（深底白字）

    动态布局：cmd 框高度按行数算（每行 0.32in），output 起点 = cmd 末尾 + 0.1in 间距
    背景色用 GRAY_700（深灰，比 GRAY_500 对比度高）
    """
    _add_card(slide, x, y, w, h, fill=GRAY_700, border=GRAY_700)
    cmd_lines = max(1, cmd.count("\n") + 1)
    cmd_h = Inches(0.1 + cmd_lines * 0.32)
    _add_textbox(slide, x + Inches(0.2), y + Inches(0.1), w - Inches(0.4), cmd_h,
                 cmd, size_pt=14, bold=True, color=WHITE)
    if output:
        out_y = y + Inches(0.1) + cmd_h + Inches(0.1)
        out_h = h - (out_y - y) - Inches(0.15)
        _add_textbox(slide, x + Inches(0.2), out_y, w - Inches(0.4), out_h,
                     output, size_pt=11, color=WHITE)


def build_slide_82_prepare(prs):
    s = prs.slides.add_slide(prs.slide_layouts[3])
    _title(s, "§7 · Lab 准备清单（开课前 30 min 装好）")
    items = [
        ("Claude Code ≥ v2.1.130",  "macOS / Win / Linux 都行 · brew install claude-ai-cli"),
        ("Git ≥ 2.30",                "git --version 看版本"),
        ("GitHub 账号 + SSH key",     "ssh -T git@github.com 测连通"),
        ("Python ≥ 3.10",             "python3 --version 看版本"),
        ("豆包 API key",              "火山引擎方舟 console 取 · export DOUBAO_API_KEY=..."),
        ("init-team.sh 跑通",         "clone repo 后跑一次 · 验证 hook + JSON + 必备文件"),
        ("pre-commit hook 装好",      "ln -sf ../../.claude/hooks/scan-commit.sh .git/hooks/pre-commit"),
        ("draw.io desktop（看图）",   "brew install --cask drawio · 看 41 张架构图"),
    ]
    for i, (head, body) in enumerate(items):
        y = Inches(1.6 + i * 0.65)
        _add_textbox(s, Inches(0.85), y, Inches(4.5), Inches(0.4),
                     f"✓ {head}", size_pt=15, bold=True, color=GREEN)
        _add_textbox(s, Inches(5.5), y + Inches(0.05), Inches(7.0), Inches(0.4),
                     body, size_pt=12, color=GRAY_700)
    _add_textbox(s, Inches(0.55), Inches(6.95), Inches(12.2), Inches(0.4),
                 "卡住 5 min 以上 → 找讲师 · 不要硬刚 · 你撞到的坑 = 现场 retro 素材",
                 size_pt=13, color=CORAL, align=PP_ALIGN.CENTER, bold=True)
    return s


def build_slide_83_step1_clone(prs):
    s = prs.slides.add_slide(prs.slide_layouts[3])
    _title(s, "§7 · 第 1 步 · clone + init-team.sh")
    # cmd_box h 从 2.5→3.3 in，原 2.5 不够装 cmd(3 行)+output(6 行)
    _cmd_box(s, Inches(0.55), Inches(1.6), Inches(12.2), Inches(3.3),
             "$ git clone git@github.com:org/agf.git ~/wt/agf\n$ cd ~/wt/agf\n$ ./init-team.sh",
             "预期输出：\n✓ Hook scripts present\n✓ .claude/settings.json valid JSON\n✓ 14 agent definitions found\n✓ git pre-commit installed\n→ Ready to start agent team")
    _add_textbox(s, Inches(0.55), Inches(5.2), Inches(12.2), Inches(0.5),
                 "验证：所有 ✓ → 进入下一步 · 任一 ✗ → 找讲师",
                 size_pt=15, color=NAVY, bold=True, align=PP_ALIGN.CENTER)
    return s


def build_slide_84_step2_topic(prs):
    s = prs.slides.add_slide(prs.slide_layouts[3])
    _title(s, "§7 · 第 2 步 · 3 道 AI 题选一")
    # 缩短 desc 到 2 行（合并第 3 行说明到第 2 行），避免 3 行折溢出
    topics = [
        ("①  旅游明信片", "上传照片 + 一句话 → 200 字文案 + 卡片图\n豆包 Vision + LLM + Seedream（与今天主线一致）", CORAL, "推荐 P1 / P2"),
        ("②  产品概念海报", "输入产品描述 → 1 张概念海报 + slogan\n豆包 LLM + Seedream（简化 2 步链路）", GOLD, "P1 选"),
        ("③  运动打卡卡片", "运动数据 (跑步距离/时间) → 励志文案 + 配图\n豆包 LLM + Seedream + 动态文字渲染（含数据可视化）", BLUE_ACCENT, "推荐 P3"),
    ]
    # card 高 1.5→1.7 / 间距 1.6→1.85，留足 desc 2 行 + padding
    # desc width 8.5→7.8，与右侧 who 拉开间距至 0.4 in
    for i, (head, desc, color, who) in enumerate(topics):
        y = Inches(1.7 + i * 1.85)
        _add_card(s, Inches(0.55), y, Inches(12.2), Inches(1.7),
                  fill=WHITE, border=color, accent=color)
        _add_textbox(s, Inches(0.85), y + Inches(0.15), Inches(3.5), Inches(0.55),
                     head, size_pt=20, bold=True, color=color)
        _add_textbox(s, Inches(0.85), y + Inches(0.75), Inches(8.0), Inches(0.9),
                     desc, size_pt=12, color=GRAY_700)
        _add_textbox(s, Inches(9.1), y + Inches(0.65), Inches(3.0), Inches(0.55),
                     f"{who}", size_pt=13, bold=True, color=NAVY)
    return s


def build_slide_85_step3_team_start(prs):
    s = prs.slides.add_slide(prs.slide_layouts[3])
    _title(s, "§7 · 第 3 步 · /agf-team-start 启动")
    _cmd_box(s, Inches(0.55), Inches(1.6), Inches(12.2), Inches(2.0),
             "$ claude\n> /agf-team-start \"做一个旅游明信片生成器\"",
             "预期：Claude 调 agf-team-start skill\n→ 启动 Team Mode\n→ 自动 spawn product-lead 作 Lead\n→ 进入 brainstorming 4 轮澄清")
    _add_textbox(s, Inches(0.55), Inches(3.9), Inches(12.2), Inches(0.5),
                 "🪟 另开终端：./tools/team-dashboard/start.sh",
                 size_pt=16, bold=True, color=NAVY)
    _cmd_box(s, Inches(0.55), Inches(4.5), Inches(12.2), Inches(1.5),
             "$ cd tools/team-dashboard && ./start.sh",
             "→ 浏览器自动打开 http://localhost:3000\n→ 看 SSE 实时同事消息 + progress / 阶段门状态")
    _add_textbox(s, Inches(0.55), Inches(6.3), Inches(12.2), Inches(0.5),
                 "dashboard 是零侵入观察台 · 关掉不影响 deck 流程",
                 size_pt=13, color=GRAY_700, align=PP_ALIGN.CENTER)
    return s


def build_slide_86_step4_pl_prd(prs):
    s = prs.slides.add_slide(prs.slide_layouts[3])
    _title(s, "§7 · 第 4 步 · 观察 PL 写 PRD + 派单")
    _add_textbox(s, Inches(0.55), Inches(1.6), Inches(12.2), Inches(0.6),
                 "🪟 dashboard 上你会看到（自动发生）：",
                 size_pt=18, bold=True, color=NAVY)
    steps = [
        ("①  PL 调 brainstorming",   "对用户问 4-5 轮问题：风格、cost、分享形态等"),
        ("②  PL 写 PRD",              "调 agf-writing-prd skill · 输出 docs/prd/postcard-2026-05-16.md"),
        ("③  PL 拆 task",             "按角色边界切（FE / BE / AI-Agent / ML 各一）"),
        ("④  PL 派单",                "SendMessage 6 段 schema · 触发 validate-task-schema hook"),
        ("⑤  PL Standby",             "等待 dev 进度 · 中途答疑"),
    ]
    from build_main import rotate5
    for i, (head, body) in enumerate(steps):
        y = Inches(2.4 + i * 0.85)
        c = rotate5(i)
        _add_card(s, Inches(0.55), y, Inches(12.2), Inches(0.75),
                  fill=WHITE, border=c, accent=c)
        _add_textbox(s, Inches(0.85), y + Inches(0.1), Inches(3.5), Inches(0.55),
                     head, size_pt=17, bold=True, color=c)
        _add_textbox(s, Inches(4.5), y + Inches(0.18), Inches(8.0), Inches(0.45),
                     body, size_pt=13, color=GRAY_700)
    return s


def build_slide_87_step5_ai_agent(prs):
    s = prs.slides.add_slide(prs.slide_layouts[3])
    _title(s, "§7 · 第 5 步 · 跟 ai-agent-dev 跑 Vision 链路")
    _add_textbox(s, Inches(0.55), Inches(1.6), Inches(12.2), Inches(0.5),
                 "dashboard 上你会看到 ai-agent-dev 自动：",
                 size_pt=17, bold=True, color=NAVY)
    items = [
        ("Plan Mode？", "本任务不触发 · 直接进入实施"),
        ("写 prompt 文件", "backend/app/agents/postcard_prompts/v1_vision.md 等 3 文件"),
        ("写代码", "backend/app/agents/postcard.py · 三步链路实现"),
        ("Unit test", "tests/unit/test_postcard_*.py · 12 用例 · 全过"),
        ("SIT 自跑", "调用 agf-running-sit-tests skill · 跑 5 道盲测"),
        ("写 progress", "progress/ai-agent-dev.md · 含 AC 自验 + SIT 证据段"),
        ("发 PR", "feature/postcard-link → @code-reviewer review"),
    ]
    for i, (head, body) in enumerate(items):
        y = Inches(2.3 + i * 0.65)
        _add_textbox(s, Inches(0.85), y, Inches(3.5), Inches(0.4),
                     f"▎ {head}", size_pt=14, bold=True, color=NAVY)
        _add_textbox(s, Inches(4.5), y + Inches(0.05), Inches(8.0), Inches(0.4),
                     body, size_pt=12, color=GRAY_700)
    return s


def build_slide_88_step6_worktree(prs):
    s = prs.slides.add_slide(prs.slide_layouts[3])
    _title(s, "§7 · 第 6 步 · worktree 看并行")
    _cmd_box(s, Inches(0.55), Inches(1.6), Inches(12.2), Inches(3.0),
             "$ ls ~/wt/ | grep agf",
             "agf/                  ← main worktree (PL 在这里)\nagf-postcard-ai/      ← ai-agent-dev 在这里（feature/postcard-link）\nagf-postcard-be/      ← backend-dev 在这里（feature/postcard-be）\nagf-postcard-fe/      ← frontend-dev 在这里（feature/postcard-fe）")
    _add_textbox(s, Inches(0.55), Inches(4.9), Inches(12.2), Inches(0.5),
                 "三个 dev 并行写代码 · 改不同文件 · 无文件锁冲突",
                 size_pt=16, color=NAVY, align=PP_ALIGN.CENTER, bold=True)
    _cmd_box(s, Inches(0.55), Inches(5.5), Inches(12.2), Inches(1.7),
             "$ git -C ~/wt/agf-postcard-ai branch --show-current\n$ git -C ~/wt/agf-postcard-be branch --show-current",
             "feature/postcard-link\nfeature/postcard-be")
    return s


def build_slide_89_step7_review(prs):
    s = prs.slides.add_slide(prs.slide_layouts[3])
    _title(s, "§7 · 第 7 步 · code review + SIT Audit")
    _add_textbox(s, Inches(0.55), Inches(1.6), Inches(12.2), Inches(0.5),
                 "🪟 dashboard 上 code-reviewer 自动：",
                 size_pt=17, bold=True, color=NAVY)
    actions = [
        ("①  接 PR 通知", "@code-reviewer 收到 PR #287 message"),
        ("②  review 代码", "看 backend/app/agents/postcard.py 实现 · 命名 / 复杂度 / 边界"),
        ("③  audit SIT 证据", "对照 progress/ai-agent-dev.md 的 4 项 SIT 证据"),
        ("④  写报告", "调 skill · 输出 docs/reviews/postcard-link-2026-05-17.md"),
        ("⑤  双 verdict", "代码 verdict + SIT Audit verdict 独立"),
        ("⑥  发 review", "PR comment + @ai-agent-dev 待修"),
    ]
    for i, (head, body) in enumerate(actions):
        y = Inches(2.3 + i * 0.75)
        _add_card(s, Inches(0.55), y, Inches(12.2), Inches(0.65),
                  fill=WHITE, border=BLUE_ACCENT, accent=BLUE_ACCENT)
        _add_textbox(s, Inches(0.85), y + Inches(0.1), Inches(3.0), Inches(0.45),
                     head, size_pt=16, bold=True, color=NAVY)
        _add_textbox(s, Inches(4.0), y + Inches(0.17), Inches(8.5), Inches(0.4),
                     body, size_pt=13, color=GRAY_700)
    return s


def build_slide_90_step8_uat(prs):
    s = prs.slides.add_slide(prs.slide_layouts[3])
    _title(s, "§7 · 第 8 步 · E2E + UAT 签字")
    actions = [
        ("①  qa-engineer 启动 E2E", "调 chrome-devtools-mcp · 跑自动化 + 5 道盲测", BLUE_ACCENT),
        ("②  qa 写 E2E 报告",       "docs/qa/postcard-e2e-2026-05-18.md · 4/5 通过", BLUE_ACCENT),
        ("③  PL 通知业务方 UAT",     "Notion 表 · 3 业务方 48h 内填评分", CORAL),
        ("④  qa 写 UAT 报告",        "docs/qa/postcard-uat-2026-05-19.md · D4 决策树跑通", CORAL),
        ("⑤  PL 业务签字",            "Pass · 触发 archive-progress.sh", GREEN),
    ]
    for i, (head, body, color) in enumerate(actions):
        y = Inches(1.7 + i * 1.0)
        _add_card(s, Inches(0.55), y, Inches(12.2), Inches(0.85),
                  fill=WHITE, border=color, accent=color)
        _add_textbox(s, Inches(0.85), y + Inches(0.15), Inches(3.5), Inches(0.55),
                     head, size_pt=18, bold=True, color=color)
        _add_textbox(s, Inches(4.5), y + Inches(0.22), Inches(8.0), Inches(0.5),
                     body, size_pt=13, color=GRAY_700)
    _add_textbox(s, Inches(0.55), Inches(6.9), Inches(12.2), Inches(0.4),
                 "至此 feature 业务签字完成 · 进入 release 阶段（第 9 步）",
                 size_pt=14, color=CORAL, align=PP_ALIGN.CENTER, bold=True)
    return s


def build_slide_91_step9_release(prs):
    s = prs.slides.add_slide(prs.slide_layouts[3])
    _title(s, "§7 · 第 9 步 · CHANGELOG + tag + Release + retro（全套）")
    steps = [
        ("1. 写 CHANGELOG.md",   "Keep a Changelog 6 节（Added / Fixed 等）"),
        ("2. git tag -a v1.0.0", "annotation 含 tagged-along commits（同会话内）"),
        ("3. git push --tags",   "推 tag 到远程"),
        ("4. gh release create", "v1.0.0 --notes-file CHANGELOG.md --latest"),
        ("5. /agf-release-retro v1.0.0", "MAJOR 强制 · 7 步 retro · Improve 必 Owner+Due"),
    ]
    for i, (head, body) in enumerate(steps):
        y = Inches(1.7 + i * 1.0)
        _add_card(s, Inches(0.55), y, Inches(12.2), Inches(0.85),
                  fill=GRAY_500, border=GRAY_500)
        _add_textbox(s, Inches(0.85), y + Inches(0.15), Inches(4.5), Inches(0.55),
                     head, size_pt=18, bold=True, color=WHITE)
        _add_textbox(s, Inches(5.5), y + Inches(0.22), Inches(7.0), Inches(0.5),
                     body, size_pt=13, color=WHITE)
    _add_textbox(s, Inches(0.55), Inches(6.9), Inches(12.2), Inches(0.4),
                 "5 步全跑通 = Lab 完成 · 你已实战完整 feature 闭环",
                 size_pt=14, color=GREEN, align=PP_ALIGN.CENTER, bold=True)
    return s


def build_slide_92_pitfalls(prs):
    s = prs.slides.add_slide(prs.slide_layouts[3])
    _title(s, "§7 · 常见踩坑 Q&A · 现场命中先举手")
    # PNG 3200×1730 (ratio 1.85) · 按 height 5.8 居中
    _add_centered_image(s, "G4-eight-pitfalls.png", top_inch=1.4, height_inch=5.8)
    return s


def build(prs):
    """构建 §6 11 张内容 slide (slide 82-92)"""
    build_slide_82_prepare(prs)
    build_slide_83_step1_clone(prs)
    build_slide_84_step2_topic(prs)
    build_slide_85_step3_team_start(prs)
    build_slide_86_step4_pl_prd(prs)
    build_slide_87_step5_ai_agent(prs)
    build_slide_88_step6_worktree(prs)
    build_slide_89_step7_review(prs)
    build_slide_90_step8_uat(prs)
    build_slide_91_step9_release(prs)
    build_slide_92_pitfalls(prs)


def build_with_checkins(prs, build_checkin_page):
    """v1.1: 构建 §6 11 内容 + 2 check-in（第 3 步后 + 第 6 步后）= 13 张"""
    build_slide_82_prepare(prs)
    build_slide_83_step1_clone(prs)
    build_slide_84_step2_topic(prs)
    build_slide_85_step3_team_start(prs)
    # check-in 1: 第 3 步后
    build_checkin_page(prs, step_done=3, total_steps=9,
                       action_hint="跑通的请举手 · 卡住的请举另一只手",
                       fail_safe="第 3 步常见卡点：\n· claude code 没装到 v2.1.130（重装一次）\n· agf-team-start skill 没找到（检查 .claude/skills/）\n· 豆包 API key 写到了 OPENAI_API_KEY（改成 DOUBAO_API_KEY）")
    build_slide_86_step4_pl_prd(prs)
    build_slide_87_step5_ai_agent(prs)
    build_slide_88_step6_worktree(prs)
    # check-in 2: 第 6 步后
    build_checkin_page(prs, step_done=6, total_steps=9,
                       action_hint="worktree 看到 3 个 dev 并行的请举手",
                       fail_safe="第 6 步常见卡点：\n· git worktree 命令报错（git 版本 < 2.30 升级）\n· 看不到 3 个目录（PL 派单失败 → 看 dashboard SendMessage 是否成功）\n· 卡 5 min 以上请举手 · 讲师过来 1v1")
    build_slide_89_step7_review(prs)
    build_slide_90_step8_uat(prs)
    build_slide_91_step9_release(prs)
    build_slide_92_pitfalls(prs)
