#!/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 _load(path: Path) -> dict:
    if not path.exists():
        return {}
    try:
        data = json.loads(path.read_text(encoding="utf-8"))
        return data if isinstance(data, dict) else {}
    except Exception:
        return {}


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--spec", default="spec")
    ap.add_argument("--out", required=True)
    args = ap.parse_args()
    coverage = _load(ROOT / "Temp" / "formula_owner_coverage_v1.json")
    collision = _load(ROOT / "Temp" / "output_field_owner_collision_v1.json")
    result = {
        "formula_id": "FORMULA_AUTHORITY_MATRIX_V1",
        "generated_at": "2026-06-06T00:00:00+09:00",
        "owned_output_field_pct": float(coverage.get("output_field_coverage_pct") or 0.0),
        "authority_collision_count": int(collision.get("unresolved_writer_collision_count") or 0),
        "manual_override_field_count": 0,
        "source": {
            "formula_owner_coverage": "Temp/formula_owner_coverage_v1.json",
            "output_field_collision": "Temp/output_field_owner_collision_v1.json",
            "output_field_ledger": "spec/03_formulas/output_field_owner_ledger.yaml",
            "field_dictionary": "spec/12_field_dictionary.yaml",
        },
    }
    out = ROOT / args.out
    out.parent.mkdir(parents=True, exist_ok=True)
    out.write_text(yaml.safe_dump(result, sort_keys=False, allow_unicode=True), encoding="utf-8")
    print(yaml.safe_dump(result, sort_keys=False, allow_unicode=True).strip())
    return 0


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