#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Summarize design check failures into a tiny repair batch.

The PPT workflow can produce dozens of design_budget/design_style findings.
Weak agents often burn all turns trying to repair the whole report. This helper
turns the current recheck JSON into a page-limited batch so the workflow can
repair 1-3 pages per round and continue after a bounded number of rounds.
"""

from __future__ import annotations

import argparse
import json
import re
from collections import defaultdict
from pathlib import Path
from typing import Any


PAGE_PATTERNS = [
    re.compile(r"第\s*(\d+)\s*页"),
    re.compile(r"\bpage\s*(\d+)\b", re.IGNORECASE),
    re.compile(r"\b页\s*(\d+)\b"),
]


def _load_json(path: Path, default: Any) -> Any:
    if not path.exists():
        return default
    try:
        return json.loads(path.read_text(encoding="utf-8"))
    except Exception:
        return default


def _page_from_line(line: str) -> int | None:
    for pattern in PAGE_PATTERNS:
        match = pattern.search(line)
        if match:
            try:
                return int(match.group(1))
            except ValueError:
                return None
    return None


def _collect_issues(report: dict[str, Any]) -> dict[int, list[str]]:
    by_page: dict[int, list[str]] = defaultdict(list)
    for key in ("style_log", "budget_log"):
        text = str(report.get(key) or "")
        for raw_line in text.splitlines():
            line = raw_line.strip()
            if not line:
                continue
            page = _page_from_line(line)
            if page is None:
                continue
            # Keep the actionable portion short. The full report remains on disk.
            by_page[page].append(line[:420])
    return dict(by_page)


def _page_title_map(design: dict[str, Any]) -> dict[int, str]:
    titles: dict[int, str] = {}
    for page in design.get("pages", []) if isinstance(design, dict) else []:
        if not isinstance(page, dict):
            continue
        try:
            page_no = int(page.get("page"))
        except Exception:
            continue
        titles[page_no] = str(page.get("title") or page.get("one_sentence_takeaway") or "")
    return titles


def make_hints(build: Path, max_pages: int) -> tuple[dict[str, Any], str]:
    report = _load_json(build / "design_review_recheck.json", {})
    design = _load_json(build / "design.json", {})
    issues_by_page = _collect_issues(report if isinstance(report, dict) else {})
    titles = _page_title_map(design if isinstance(design, dict) else {})

    ranked = sorted(
        issues_by_page.items(),
        key=lambda item: (-len(item[1]), item[0]),
    )
    selected = ranked[:max_pages]
    batch_pages = []
    for page_no, issues in selected:
        batch_pages.append(
            {
                "page": page_no,
                "title": titles.get(page_no, ""),
                "issue_count": len(issues),
                "issues": issues[:8],
            }
        )

    payload = {
        "ok": bool(report.get("ok")) if isinstance(report, dict) else False,
        "budget_ok": bool(report.get("budget_ok")) if isinstance(report, dict) else False,
        "style_ok": bool(report.get("style_ok")) if isinstance(report, dict) else False,
        "max_pages": max_pages,
        "total_pages_with_issues": len(issues_by_page),
        "total_issue_lines": sum(len(v) for v in issues_by_page.values()),
        "pages": batch_pages,
        "auto_repair_guidance": [
            "只修本批页，不扩散重写全稿。",
            "先减字、合并要点、补齐 composition_style/visual_focus/text_zone/copy_budget 等字段。",
            "禁止为填满页面新增卡片墙、表格墙、大白/灰浮动面板。",
            "无客户图且非 HTML/SVG 精确信息页，必须规划真实 AI 语义图。",
            "数据/流程/架构/关系图继续用 HTML/SVG，不交给 AI 生图。",
        ],
    }

    lines = [
        "# 设计短修复批次",
        "",
        f"- ok: {payload['ok']}",
        f"- budget_ok: {payload['budget_ok']}",
        f"- style_ok: {payload['style_ok']}",
        f"- 本批最多修复页数: {max_pages}",
        f"- 有问题页数: {payload['total_pages_with_issues']}",
        f"- 问题行数: {payload['total_issue_lines']}",
        "",
        "## 修复原则",
        "",
    ]
    for item in payload["auto_repair_guidance"]:
        lines.append(f"- {item}")
    lines.extend(["", "## 本批页", ""])
    if not batch_pages:
        lines.append("当前没有可定位到页号的问题。若 recheck 仍失败，只做全局字段/格式修复。")
    for page in batch_pages:
        lines.append(f"### 第 {page['page']} 页 {page['title']}")
        lines.append(f"- 问题数: {page['issue_count']}")
        for issue in page["issues"]:
            lines.append(f"- {issue}")
        lines.append("")
    return payload, "\n".join(lines).rstrip() + "\n"


def main() -> int:
    parser = argparse.ArgumentParser(description="Create a small design repair batch from recheck reports.")
    parser.add_argument("--build", default="./build", help="Build directory")
    parser.add_argument("--max-pages", type=int, default=3, help="Maximum pages to include")
    args = parser.parse_args()

    build = Path(args.build)
    build.mkdir(parents=True, exist_ok=True)
    payload, markdown = make_hints(build, max(1, args.max_pages))
    (build / "design_repair_batch.json").write_text(
        json.dumps(payload, ensure_ascii=False, indent=2),
        encoding="utf-8",
    )
    (build / "design_repair_batch.md").write_text(markdown, encoding="utf-8")
    print("DESIGN_REPAIR_BATCH_OK")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
