\
from __future__ import annotations
import argparse, os
from .casehub.scan import scan_cases
from .casehub.registry import load_registry, upsert_registry, write_registry_csv
from .casehub.report import write_index_md

def main(argv=None) -> int:
    p = argparse.ArgumentParser(prog="toughanimator-casehub", description="Case registry + index generator for toughanimator.")
    sub = p.add_subparsers(dest="cmd", required=True)

    p_scan = sub.add_parser("scan", help="Scan a cases root and update registry/index.")
    p_scan.add_argument("cases_root", help="Root directory containing case folders (each with config.json).")
    p_scan.add_argument("--out", default="cases", help="Output folder for registry/index (default: ./cases)")
    p_scan.add_argument("--registry", default="registry.csv", help="Registry filename (default: registry.csv)")
    p_scan.add_argument("--index", default="INDEX.md", help="Index filename (default: INDEX.md)")

    args = p.parse_args(argv)

    if args.cmd == "scan":
        metas = scan_cases(args.cases_root)
        out_dir = os.path.abspath(args.out)
        reg_path = os.path.join(out_dir, args.registry)
        idx_path = os.path.join(out_dir, args.index)

        reg = load_registry(reg_path)
        reg = upsert_registry(reg, metas)
        write_registry_csv(reg_path, reg)
        write_index_md(idx_path, reg)

        print(f"Scanned {len(metas)} case(s).")
        print(f"Wrote: {reg_path}")
        print(f"Wrote: {idx_path}")
        return 0

    return 1

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