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

import argparse
import json
from pathlib import Path

import yaml


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


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--spec", default="spec/15_account_snapshot_contract.yaml")
    args = ap.parse_args()
    data = yaml.safe_load((ROOT / args.spec).read_text(encoding="utf-8")) or {}
    contract = data.get("account_snapshot_contract") or {}
    required = {"holdings_screen", "cash_screen", "open_orders_screen", "contribution_limit_screen"}
    missing_groups = sorted(required - set((contract.get("required_capture_groups") or {}).keys()))
    canonical = contract.get("canonical_fields") or {}
    needed = ["captured_at", "account", "account_type", "holding_quantity", "average_cost", "current_price", "market_value", "immediate_cash", "settlement_cash_d2", "available_cash", "parse_status"]
    missing_fields = [field for field in needed if field not in canonical]
    result = {
        "formula_id": "ACCOUNT_SNAPSHOT_CONTRACT_V1",
        "missing_capture_group_count": len(missing_groups),
        "missing_field_count": len(missing_fields),
        "gate": "PASS" if not missing_groups and not missing_fields else "FAIL",
    }
    out = ROOT / "Temp" / "account_snapshot_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 result["gate"] == "PASS" else 1


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