#!/usr/bin/env python3
import argparse
import sys
from pathlib import Path
import yaml

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


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--dir", default="spec/formulas/domains")
    args = parser.parse_args()

    domains_dir = ROOT / args.dir
    if not domains_dir.exists():
        print(f"Directory not found: {domains_dir}")
        return 1

    required_fields = [
        "owner",
        "lifecycle_state",
        "input_fields",
        "output_fields",
        "missing_policy",
        "golden_cases"
    ]

    missing_count = 0
    yaml_files = list(domains_dir.glob("*.yaml"))
    
    # Exclude manifest.yaml if present
    yaml_files = [f for f in yaml_files if f.name != "manifest.yaml"]

    for yf in yaml_files:
        try:
            data = yaml.safe_load(yf.read_text(encoding="utf-8"))
        except Exception as e:
            print(f"Error reading {yf.name}: {e}")
            continue

        if not isinstance(data, dict):
            continue

        formulas = data.get("formulas") or {}
        for fid, formula in formulas.items():
            if not isinstance(formula, dict):
                print(f"Formula {fid} in {yf.name} is not a dictionary")
                missing_count += len(required_fields)
                continue

            for field in required_fields:
                if field not in formula:
                    print(f"Formula {fid} in {yf.name} is missing required field: {field}")
                    missing_count += 1

    print(f"Total missing required contract fields: {missing_count}")
    return 0 if missing_count == 0 else 1


if __name__ == "__main__":
    sys.exit(main())
