#!/usr/bin/env python3
"""Generate agents/evidence/notes/discovery-baseline.md for Phase 0.1."""
from __future__ import annotations

import datetime as _dt
import pathlib
import re
import sys
from collections import Counter

ROOT = pathlib.Path(__file__).resolve().parents[2]
SRC = ROOT / ".agent-src.uncondensed"


def _frontmatter(path: pathlib.Path) -> dict[str, str]:
    text = path.read_text(encoding="utf-8", errors="replace")
    m = re.match(r"^---\n(.*?)\n---\n", text, re.DOTALL)
    if not m:
        return {}
    out: dict[str, str] = {}
    for line in m.group(1).splitlines():
        if ":" in line and not line.startswith(" "):
            k, _, v = line.partition(":")
            out[k.strip()] = v.strip().strip('"').strip("'")
    return out


def main() -> int:
    skills = sorted((SRC / "skills").rglob("SKILL.md"))
    rules = sorted((SRC / "rules").rglob("*.md"))
    commands = sorted((SRC / "commands").rglob("*.md"))
    templates = sorted((SRC / "templates").rglob("*")) if (SRC / "templates").exists() else []
    templates = [p for p in templates if p.is_file()]

    domains: Counter[str] = Counter()
    no_domain = 0
    for s in skills:
        fm = _frontmatter(s)
        d = fm.get("domain")
        if d:
            domains[d] += 1
        else:
            no_domain += 1

    out = []
    out.append("# Discovery Baseline — Inventory (Phase 0.1)\n")
    out.append(
        f"> Generated by `scripts/gen_discovery_baseline.py` on "
        f"{_dt.datetime.now(_dt.timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')}.\n"
    )
    out.append(
        "> Frozen reference for the Phase 2 scanner — the `no domain` tally below must match the\n"
        "> first scanner run's `unassigned[]` count within ±5% (Phase 2.4 acceptance).\n"
    )

    out.append("## Counts by category\n")
    out.append("| Category | Path | Count |")
    out.append("|---|---|---|")
    out.append(f"| Skills | `.agent-src.uncondensed/skills/*/SKILL.md` | {len(skills)} |")
    out.append(f"| Rules | `.agent-src.uncondensed/rules/**/*.md` | {len(rules)} |")
    out.append(f"| Commands | `.agent-src.uncondensed/commands/**/*.md` | {len(commands)} |")
    out.append(f"| Templates | `.agent-src.uncondensed/templates/**/*` | {len(templates)} |")
    out.append("")

    out.append("## Distinct `domain:` values (skills)\n")
    for d, n in domains.most_common():
        out.append(f"- `{d}` — {n} skill(s)")
    out.append("")

    out.append("## Skills without `domain:` (Phase 0.1 baseline)\n")
    out.append(
        f"- Count: **{no_domain}** (target for Phase 2.4 `unassigned[]` tally ±5%)"
    )
    out.append("")

    out.append("## Sample frontmatter keys (first 10 skills)\n")
    out.append("| File | name | source | domain | other keys |")
    out.append("|---|---|---|---|---|")
    interesting = {"status", "tier", "recommended_for_user_types", "cluster", "skills"}
    for s in skills[:10]:
        fm = _frontmatter(s)
        other = ",".join(sorted(k for k in fm if k in interesting))
        rel = s.relative_to(SRC)
        out.append(
            f"| `{rel}` | {fm.get('name','')} | {fm.get('source','')} | "
            f"{fm.get('domain','')} | {other} |"
        )
    out.append("")

    out.append("## Sample rules (first 10)\n")
    out.append("| File | type | tier | source |")
    out.append("|---|---|---|---|")
    for r in rules[:10]:
        fm = _frontmatter(r)
        rel = r.relative_to(SRC)
        out.append(
            f"| `{rel}` | {fm.get('type','')} | {fm.get('tier','')} | {fm.get('source','')} |"
        )
    out.append("")

    out.append("## Sample commands (first 10)\n")
    out.append("| File | name | tier | cluster |")
    out.append("|---|---|---|---|")
    for c in commands[:10]:
        fm = _frontmatter(c)
        rel = c.relative_to(SRC)
        out.append(
            f"| `{rel}` | {fm.get('name','')} | {fm.get('tier','')} | {fm.get('cluster','')} |"
        )
    out.append("")

    out.append("## Notes\n")
    out.append("- Every skill carries `domain:` today — Phase 4 mapping uses it as primary signal.")
    out.append("- Rules use `type` (always | auto) + `tier` (safety-floor | kernel | …); no `domain:` today.")
    out.append("- Commands use `tier` + `cluster`; no `domain:` today.")
    out.append("- Templates have no consistent frontmatter; Phase 4 quarantines them in `unassigned-artefacts.yml`.")
    out.append("")

    dest = ROOT / "agents" / "notes" / "discovery-baseline.md"
    dest.parent.mkdir(parents=True, exist_ok=True)
    dest.write_text("\n".join(out), encoding="utf-8")
    print(f"wrote {dest} — {len(out)} lines")
    return 0


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