\
from __future__ import annotations
import os, collections, datetime
from typing import Dict, List
from .registry import REGISTRY_FIELDS

def _group_key(row: dict) -> tuple:
    return (row.get("engine","unknown"), row.get("io_signature","unknown"), row.get("fields_hash",""))

def write_index_md(path: str, registry: Dict[str, dict]) -> None:
    os.makedirs(os.path.dirname(path), exist_ok=True)
    rows = list(registry.values())
    total = len(rows)
    by_status = collections.Counter(r.get("status","unknown") or "unknown" for r in rows)
    by_engine = collections.Counter(r.get("engine","unknown") or "unknown" for r in rows)

    groups = collections.defaultdict(list)
    for r in rows:
        groups[_group_key(r)].append(r)

    # sort groups by size desc
    group_items = sorted(groups.items(), key=lambda kv: (-len(kv[1]), kv[0][0], kv[0][1]))

    today = datetime.datetime.now().strftime("%Y-%m-%d")
    lines = []
    lines.append(f"# toughanimator CaseHub Index\n")
    lines.append(f"_Generated: {today}_\n")
    lines.append(f"## Summary\n")
    lines.append(f"- Total cases: **{total}**\n")
    lines.append(f"- Status: " + ", ".join([f"**{k}** {v}" for k,v in by_status.most_common()]) + "\n")
    lines.append(f"- Engine: " + ", ".join([f"**{k}** {v}" for k,v in by_engine.most_common()]) + "\n")

    lines.append("\n## Coverage by signature (engine × io_signature × fields_hash)\n")
    lines.append("| # | engine | io_signature | fields_hash | cases | example |\n")
    lines.append("|---:|---|---|---|---:|---|\n")
    for i,(k, items) in enumerate(group_items[:200], start=1):
        engine, sig, fhash = k
        example = items[0].get("case_name","")
        lines.append(f"| {i} | {engine} | `{sig}` | `{(fhash or '')[:10]}` | {len(items)} | {example} |\n")

    # recent seen
    rows_sorted = sorted(rows, key=lambda r: (r.get("last_seen",""), r.get("case_name","")), reverse=True)
    lines.append("\n## Recently seen\n")
    lines.append("| last_seen | engine | status | case_name |\n")
    lines.append("|---|---|---|---|\n")
    for r in rows_sorted[:30]:
        lines.append(f"| {r.get('last_seen','')} | {r.get('engine','')} | {r.get('status','')} | {r.get('case_name','')} |\n")

    # failures
    fails = [r for r in rows if (r.get("status","") or "").lower() in {"fail","failed","error"}]
    if fails:
        lines.append("\n## Failures\n")
        lines.append("| engine | case_name | tested_on | notes |\n")
        lines.append("|---|---|---|---|\n")
        for r in sorted(fails, key=lambda r: (r.get("engine",""), r.get("case_name",""))):
            note = (r.get("notes","") or "").replace("\n"," ")
            if len(note) > 80: note = note[:77] + "..."
            lines.append(f"| {r.get('engine','')} | {r.get('case_name','')} | {r.get('tested_on','')} | {note} |\n")

    with open(path, "w", encoding="utf-8") as f:
        f.writelines(lines)
