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.reporting.fonts import resolve_quarto_fonts
from scripts.reporting.references import build_references_block
from scripts.number_citations import number_citations


def test_build_references_block_uses_only_cited_sources(tmp_path: Path) -> None:
    sources = tmp_path / "sources.jsonl"
    rows = [
        {"id": "src_001", "authors": ["A"], "year": 2024, "title": "Used", "venue": "NEJM", "url": "https://example.com/1"},
        {"id": "src_002", "authors": ["B"], "year": 2023, "title": "Unused", "venue": "Lancet", "url": "https://example.com/2"},
    ]
    sources.write_text("\n".join(json.dumps(row, ensure_ascii=False) for row in rows), encoding="utf-8")

    block = build_references_block(sources, "正文引用 [src_001]。")

    assert "Used" in block
    assert "Unused" not in block


def test_resolve_quarto_fonts_returns_stable_defaults_for_missing_dir(tmp_path: Path) -> None:
    fonts = resolve_quarto_fonts(tmp_path / "missing")

    assert fonts.main_font == "Source Han Serif CN"
    assert fonts.sans_font == "Source Han Sans CN"
    assert fonts.requires_system_fonts is True


def test_number_citations_replaces_source_ids_and_keeps_url() -> None:
    text = "# 报告\n\n关键判断。[src_a, src_b]\n\n## 参考文献\n\n旧列表\n"
    sources = {
        "src_a": {"title": "法规 A", "url": "https://example.com/a"},
        "src_b": {"title": "指南 B", "url": "https://example.com/b"},
    }

    numbered, records = number_citations(text=text, sources=sources)

    assert "关键判断。<sup>[1, 2]</sup>" in numbered
    assert "[src_a" not in numbered
    assert "## 参考来源清单" in numbered
    assert "1. 法规 A. https://example.com/a" in numbered
    assert "旧列表" not in numbered
    assert [record["source_id"] for record in records] == ["src_a", "src_b"]


def test_number_citations_deduplicates_same_underlying_source() -> None:
    text = "甲。[src_a]\n\n乙。[src_b, src_c]\n"
    sources = {
        "src_a": {"title": "同一报告 OCR", "path": "phase0/report.md"},
        "src_b": {"title": "同一报告", "path": "phase0/report.md"},
        "src_c": {"title": "法规 C", "url": "https://example.com/c"},
    }

    numbered, records = number_citations(text=text, sources=sources)

    assert "甲。<sup>[1]</sup>" in numbered
    assert "乙。<sup>[1, 2]</sup>" in numbered
    assert numbered.count("同一报告") == 1
    assert "同一报告 OCR" not in numbered
    assert len(records) == 2
    assert records[0]["source_ids"] == ["src_a", "src_b"]
