from __future__ import annotations

import json
import sys
from pathlib import Path

REPO_ROOT = Path(__file__).resolve().parents[1]
if str(REPO_ROOT) not in sys.path:
    sys.path.insert(0, str(REPO_ROOT))

from scripts.runtime.review import (
    build_phase3_model_review_context,
    build_phase3_model_critique,
    phase3_model_review_system_prompt,
)


class FakeClient:
    def __init__(self) -> None:
        self.calls: list[dict[str, object]] = []

    def chat_complete(self, **kwargs) -> str:
        self.calls.append(kwargs)
        return "# Phase 3 Opus 4.7 独立审校\n\n## 总体判定\n\n回炉 Phase2。\n"


def make_project(tmp_path: Path) -> Path:
    project = tmp_path / "project"
    (project / "phase1").mkdir(parents=True)
    (project / "phase2/drafts").mkdir(parents=True)
    (project / "phase2/compressed_findings").mkdir(parents=True)
    (project / "manifest.json").write_text(
        json.dumps({"topic": "白帆测试项目", "phase3": {}}, ensure_ascii=False),
        encoding="utf-8",
    )
    (project / "phase1/framework.md").write_text("## 第1章 质量体系判断\n", encoding="utf-8")
    (project / "phase2/drafts/ch01.md").write_text("## 质量体系判断\n\n正文。[src_001]\n", encoding="utf-8")
    (project / "phase2/sources.jsonl").write_text('{"id":"src_001","title":"来源","url":"https://www.fda.gov/example"}\n', encoding="utf-8")
    (project / "phase2/compressed_findings/ch01.json").write_text(
        json.dumps(
            {
                "chapter_id": "ch01",
                "chapter_title": "质量体系判断",
                "packet_ids": ["ch01-a"],
                "chapter_thesis": "质量体系需要补证据",
                "key_findings": [],
                "evidence_landings": [],
                "counter_evidence": [],
                "source_ids": ["src_001"],
                "open_questions": [],
                "writing_plan": [],
            },
            ensure_ascii=False,
        ),
        encoding="utf-8",
    )
    return project


def test_phase3_model_context_contains_structured_inputs(tmp_path: Path) -> None:
    project = make_project(tmp_path)

    context = build_phase3_model_review_context(project)

    assert "Deterministic Review Baseline" in context
    assert "Compressed Findings" in context
    assert "Chapter Drafts" in context
    assert "src_001" in context


def test_phase3_model_review_calls_requested_model_and_writes_critique(tmp_path: Path) -> None:
    project = make_project(tmp_path)
    fake = FakeClient()

    out = build_phase3_model_critique(project, client=fake, model="zenmux-anthropic/claude-opus-4-7")

    assert out.exists()
    assert fake.calls[0]["model"] == "zenmux-anthropic/claude-opus-4-7"
    assert "独立总编审校" in fake.calls[0]["system"]
    assert "FDA/NMPA/EMA/ICH/WHO" in phase3_model_review_system_prompt()
