from __future__ import annotations

import json
import sys
from pathlib import Path


ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / "scripts"))

from check_1c_rag_freshness import compare_manifest  # noqa: E402


def test_rag_freshness_uses_official_front_matter_source_type(tmp_path: Path) -> None:
    source_dir = tmp_path / "sources"
    source_dir.mkdir()
    source = source_dir / "official.md"
    source.write_text(
        "\n".join(
            [
                "---",
                'source: "official_1c_its"',
                'source_type: "official_1c_its_glossary"',
                "---",
                "# Глоссарий",
                "",
                "Термин платформы 1С.",
            ]
        ),
        encoding="utf-8",
    )
    manifest = tmp_path / "rag_manifest.json"
    manifest.write_text(
        json.dumps(
            {
                "sources": [
                    {
                        "source_path": "official.md",
                        "source_type": "official_1c_its_glossary",
                        "file_type": "md",
                        "content_hash": "unused",
                    }
                ]
            },
            ensure_ascii=False,
        ),
        encoding="utf-8",
    )
    current = compare_manifest(source_dir, manifest)
    manifest_data = json.loads(manifest.read_text(encoding="utf-8"))
    manifest_data["sources"][0]["content_hash"] = current["changed"] and "wrong"
    from check_1c_rag_freshness import source_state

    manifest_data["sources"][0]["content_hash"] = source_state(source_dir)["official.md"]["content_hash"]
    manifest.write_text(json.dumps(manifest_data, ensure_ascii=False), encoding="utf-8")

    report = compare_manifest(source_dir, manifest)

    assert report["status"] == "fresh"
    assert report["type_changed"] == []
