#!/usr/bin/env python3
from __future__ import annotations

import json
import sys
from pathlib import Path

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


def main() -> int:
    errors: list[str] = []

    spec_path = ROOT / "spec" / "02_data_contract.yaml"
    server_path = ROOT / "src" / "quant_engine" / "snapshot_admin_server_v1.py"
    collector_path = ROOT / "src" / "quant_engine" / "kis_data_collection_v1.py"

    spec_text = spec_path.read_text(encoding="utf-8")
    server_text = server_path.read_text(encoding="utf-8")
    collector_text = collector_path.read_text(encoding="utf-8")

    required_markers = [
        ("spec/db-first", "DB 기반 수집 결과를 바탕으로 생성된 파생 보고서 증빙"),
        ("spec/db-first-xlsx", "xlsx는 HTS 잔고·거래내역 판독 또는 DB 반영 이전의 보조 감사 소스"),
        ("server/json-role", "derived_report_evidence"),
        ("server/json-evidence", "Derived JSON Evidence Preview"),
        ("server/collection-trend", "collectionTrendChart"),
        ("collector/db-canonical", "SQLite as the canonical persistence layer"),
    ]
    for name, marker in required_markers:
        haystack = {
            "spec/db-first": spec_text,
            "spec/db-first-xlsx": spec_text,
            "server/json-role": server_text,
            "server/json-evidence": server_text,
            "server/collection-trend": server_text,
            "collector/db-canonical": collector_text,
        }[name]
        if marker not in haystack:
            errors.append(f"missing marker: {name}")

    if errors:
        print(json.dumps({"gate": "FAIL", "errors": errors}, ensure_ascii=False, indent=2))
        return 1
    print(json.dumps({"gate": "PASS", "errors": []}, ensure_ascii=False, indent=2))
    return 0


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