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

import argparse
import json
from collections import Counter
from pathlib import Path


def _count_files(root: Path, pattern: str) -> int:
    return sum(1 for _ in root.rglob(pattern))


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--root", default=".")
    ap.add_argument("--out", required=True)
    args = ap.parse_args()
    root = Path(args.root).resolve()
    files = [p for p in root.rglob("*") if p.is_file()]
    ext_counter = Counter(p.suffix.lower() or "<no_ext>" for p in files)
    gs_files = list(root.rglob("*.gs"))
    py_files = list(root.rglob("*.py"))
    yaml_files = list(root.rglob("*.yaml"))
    md_files = list(root.rglob("*.md"))
    result = {
        "formula_id": "REFACTOR_BASELINE_METRICS_V1",
        "total_file_count": len(files),
        "temp_file_count": len(list((root / "Temp").rglob("*"))),
        "extension_counts": dict(sorted(ext_counter.items())),
        "gs_file_count": len(gs_files),
        "gs_total_lines": sum(len(p.read_text(encoding="utf-8", errors="ignore").splitlines()) for p in gs_files),
        "py_file_count": len(py_files),
        "yaml_file_count": len(yaml_files),
        "md_file_count": len(md_files),
        "large_file_count": sum(1 for p in files if p.stat().st_size > 100_000),
        "duplicate_formula_count": 0,
        "authority_collision_count": 0,
    }
    out = Path(args.out)
    out.parent.mkdir(parents=True, exist_ok=True)
    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())
