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

import json
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]

REQUIRED_PATTERNS = {
    ".gitea/workflows/kis_data_collection.yml": [
        "vars.KIS_APP_KEY_TEST",
        "vars.KIS_APP_SECRET_TEST",
        "vars.KIS_APP_KEY",
        "vars.KIS_APP_SECRET",
    ],
    ".gitea/workflows/qualitative_sell_strategy.yml": [
        "vars.KIS_APP_KEY_TEST",
        "vars.KIS_APP_SECRET_TEST",
        "vars.KIS_APP_KEY",
        "vars.KIS_APP_SECRET",
    ],
    ".gitea/workflows/ci.yml": [
        "vars.KIS_APP_KEY_TEST",
        "vars.KIS_APP_SECRET_TEST",
    ],
    "docs/GITEA_SECRETS_SETUP.md": [
        "Temp/kis_tokens.db",
        "TOKEN_REFRESH_SKEW_MINUTES=10",
        "python tools/inspect_kis_token_cache_v1.py --json",
    ],
    "docs/GATHERTRADINGDATA_XLSX_OPERATING_RUNBOOK.md": [
        "Temp/kis_tokens.db",
        "TOKEN_REFRESH_SKEW_MINUTES",
    ],
}



def main() -> int:
    errors: list[str] = []
    evidence: dict[str, dict[str, bool]] = {}

    for rel, patterns in REQUIRED_PATTERNS.items():
        path = ROOT / rel
        text = path.read_text(encoding="utf-8") if path.exists() else ""
        file_evidence: dict[str, bool] = {}
        if not path.exists():
            errors.append(f"missing:{rel}")
            evidence[rel] = file_evidence
            continue
        for pattern in patterns:
            found = pattern in text
            file_evidence[pattern] = found
            if not found:
                errors.append(f"{rel}:{pattern}")
        evidence[rel] = file_evidence

    result = {
        "formula_id": "GITEA_SECRETS_CONTRACT_V1",
        "gate": "PASS" if not errors else "FAIL",
        "evidence": evidence,
        "errors": errors,
    }
    out = ROOT / "Temp" / "gitea_secrets_contract_v1.json"
    out.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
    print(json.dumps(result, ensure_ascii=False, indent=2))
    return 0 if not errors else 1


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