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.methods import ResearchMethodRegistry
from scripts.runtime.orchestrator import create_phase2_task_cards
from scripts.runtime.tasks import generate_task_cards


def test_method_registry_loads_market_and_gmp_methods() -> None:
    registry = ResearchMethodRegistry()

    names = registry.list_names()

    assert "mckinsey_market" in names
    assert "gmp_gap_assessment" in names
    assert registry.get("gmp_gap_assessment").task_axes[0] == "regulatory_gap"


def test_task_cards_use_method_axes() -> None:
    framework = "## 第1章 GMP 审计差距决定整改优先级\n\n研究思路：法规、风险、CAPA。"
    registry = ResearchMethodRegistry()
    method = registry.get("gmp_gap_assessment")

    cards = generate_task_cards("gmp-test", framework, method=method)

    assert [card.topic_axis for card in cards] == method.task_axes
    assert cards[0].task_id == "ch01-regulatory_gap"


def test_orchestrator_reads_research_method_from_manifest(tmp_path: Path) -> None:
    project = tmp_path / "gmp-project"
    (project / "phase1").mkdir(parents=True)
    (project / "manifest.json").write_text(
        json.dumps({"research_method": "gmp_gap_assessment", "phase2": {}}, ensure_ascii=False),
        encoding="utf-8",
    )
    (project / "phase1" / "framework.md").write_text(
        "## 第1章 GMP 体系差距需要按法规和风险双轴定位\n\n研究思路。",
        encoding="utf-8",
    )
    (project / "phase1" / "research_brief.json").write_text(
        json.dumps(
            {
                "research_method": "gmp_gap_assessment",
                "work_language": "zh",
                "task_planning": {
                    "required_skills": ["search-gateway", "evidence-table"],
                    "search_routes_by_axis": {"regulatory_gap": ["general", "news"]},
                    "axis_prompt_briefs": {"regulatory_gap": "逐条映射法规基线与审计差距。"},
                    "stop_conditions": ["证据不足则回炉补证。"],
                },
                "materials": [{"path": "phase0/extracted/audit.md"}],
            },
            ensure_ascii=False,
        ),
        encoding="utf-8",
    )

    cards = create_phase2_task_cards(project, dry_run=True)

    assert [card["topic_axis"] for card in cards][:3] == [
        "regulatory_gap",
        "risk_classification",
        "capa_design",
    ]
    assert cards[0]["prompt_brief"] == "逐条映射法规基线与审计差距。"
    assert cards[0]["allowed_materials"] == ["phase0/extracted/audit.md"]
