#!/usr/bin/env python3
"""v0.20 Python-core regression checks."""

from __future__ import annotations

import json
import subprocess
import sys
import tempfile
from pathlib import Path


REPO_ROOT = Path(__file__).resolve().parent.parent


def run(cmd: list[str]) -> None:
    print("$ " + " ".join(cmd))
    result = subprocess.run(cmd, cwd=REPO_ROOT, check=False, text=True, capture_output=True)
    if result.stdout:
        print(result.stdout.rstrip())
    if result.stderr:
        print(result.stderr.rstrip(), file=sys.stderr)
    if result.returncode != 0:
        raise SystemExit(result.returncode)


def make_fixture(root: Path) -> Path:
    project = root / "v020-fixture"
    (project / "phase4").mkdir(parents=True, exist_ok=True)
    (project / "phase4" / "final_zh.md").write_text(
        "# v0.20 回归测试报告\n\n正文引用占位。\n",
        encoding="utf-8",
    )
    return project


def write_fixture_packet(project: Path) -> None:
    cards = json.loads((project / "phase2" / "task_cards.json").read_text(encoding="utf-8"))
    for index, card in enumerate(cards, start=1):
        source_a = f"src_{index:03d}_a"
        source_b = f"src_{index:03d}_b"
        packet = {
            "task_id": card["task_id"],
            "claims": [{"claim": f"{card['task_id']} 回归证据支持章节主线", "source_ids": [source_a]}],
            "evidence_items": [{"source_id": source_a, "summary": "权威来源支持该判断"}],
            "counter_evidence": [{"claim": "证据仍需更多来源交叉验证", "source_ids": [source_b]}],
            "source_ids": [source_a, source_b],
            "source_quality_notes": [f"{source_a} Tier 1", f"{source_b} Tier 2"],
            "open_questions": ["需要在真实项目中补充更多来源。"],
            "raw_quotes_or_notes": ["English raw note can remain here."],
            "sources": [
                {"id": source_a, "title": f"Regression Source {index}A", "url": f"https://example.com/source-{index}-a", "tier": 1},
                {"id": source_b, "title": f"Regression Source {index}B", "url": f"https://example.com/source-{index}-b", "tier": 2},
            ],
        }
        packet_path = project / card["output_packet"]
        packet_path.write_text(json.dumps(packet, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")


def main() -> int:
    python = sys.executable
    run([python, "scripts/dr.py", "skills", "validate"])
    run([python, "scripts/dr.py", "models", "--profile", "medium", "--json"])
    with tempfile.TemporaryDirectory(prefix="deep-research-v020-") as tmp:
        tmp_root = Path(tmp)
        run(
            [
                python,
                "scripts/dr.py",
                "init",
                "v0.20 fixture",
                "--slug",
                "v020-fixture",
                "--projects-dir",
                str(tmp_root),
                "--method",
                "mckinsey_market",
            ]
        )
        project = make_fixture(tmp_root)
        run([python, "scripts/dr.py", "frame", str(project)])
        assert (project / "phase1" / "research_brief.json").exists()
        run([python, "scripts/dr.py", "approve", str(project)])
        run([python, "scripts/dr.py", "research", str(project), "--workers", "2", "--axis", "literature", "--dry-run"])
        run([python, "scripts/dr.py", "research", str(project), "--workers", "2", "--axis", "literature"])
        write_fixture_packet(project)
        run([python, "scripts/dr.py", "research", str(project), "--workers", "2", "--axis", "literature", "--build-briefs"])
        assert (project / "phase2" / "compressed_findings" / "ch01.json").exists()
        run([python, "scripts/dr.py", "review", str(project)])
        run([python, "scripts/dr.py", "finalize", str(project), "--dry-run"])
    print("v0.20 regression PASS")
    return 0


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