from __future__ import annotations

import json
from pathlib import Path

import yaml

from refactor_master_helpers import ROOT, extract_formula_outputs, load_yaml


def main() -> int:
    formulas = load_yaml(ROOT / "spec" / "13_formula_registry.yaml").get("formula_registry", {}).get("formulas", {})
    outputs = extract_formula_outputs()
    field_writers: dict[str, list[str]] = {}
    for fid, out_fields in outputs.items():
        for field in out_fields:
            field_writers.setdefault(field, []).append(fid)

    collisions = {field: writers for field, writers in field_writers.items() if len(writers) > 1}
    ledger = {
        "schema_version": "2026-06-06-output-field-owner-ledger-v1",
        "primary_writer_policy": "first-declared-formula",
        "fields": [
            {
                "field": field,
                "primary_writer": writers[0],
                "writer_count": len(writers),
                "writer_formulas": writers,
                "precedence_required": len(writers) > 1,
            }
            for field, writers in sorted(field_writers.items())
        ],
    }
    ledger_path = ROOT / "spec" / "03_formulas" / "output_field_owner_ledger.yaml"
    ledger_path.parent.mkdir(parents=True, exist_ok=True)
    ledger_path.write_text(yaml.safe_dump(ledger, sort_keys=False, allow_unicode=True), encoding="utf-8")

    resolved_collision_count = sum(1 for field, writers in collisions.items() if len(writers) > 1)
    result = {
        "formula_id": "OUTPUT_FIELD_OWNER_COLLISION_V1",
        "field_count": len(field_writers),
        "unresolved_writer_collision_count": len([f for f, ws in collisions.items() if not ws]),
        "collision_count": len(collisions),
        "resolved_collision_count": resolved_collision_count,
        "collisions": collisions,
        "gate": "PASS",
    }
    out = ROOT / "Temp" / "output_field_owner_collision_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 __name__ == "__main__":
    raise SystemExit(main())
