from __future__ import annotations

import json
from pathlib import Path

import yaml

ROOT = Path(__file__).resolve().parents[1]
CONTRACT = ROOT / "spec" / "postgresql_history_contract.yaml"
OUT = ROOT / "Temp" / "postgresql_history_contract_v1.json"


def main() -> int:
    errors: list[str] = []
    if not CONTRACT.exists():
        errors.append("contract_missing")
    else:
        try:
            data = yaml.safe_load(CONTRACT.read_text(encoding="utf-8"))
        except Exception as exc:
            errors.append(f"yaml_parse_error:{exc}")
            data = {}
        if not isinstance(data, dict):
            errors.append("contract_not_mapping")
        else:
            for key in ("market_raw_history", "factor_version_history", "factor_output_history", "decision_result_history", "market_vs_engine_gap_history"):
                if key not in (data.get("domains") or {}):
                    errors.append(f"missing_domain:{key}")
            if "PostgreSQL" not in json.dumps(data, ensure_ascii=False):
                errors.append("postgresql_not_mentioned")

    result = {
        "formula_id": "POSTGRESQL_HISTORY_CONTRACT_V1",
        "gate": "PASS" if not errors else "FAIL",
        "errors": errors,
        "contract_path": str(CONTRACT.relative_to(ROOT)),
    }
    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())
