"""Generate per-agent instruction files from the single source template.

Usage:  python docs/agents/generate.py          (writes all files)
        python docs/agents/generate.py --check  (exits non-zero if any file is stale)
"""

from __future__ import annotations

import sys
from pathlib import Path

REPO = Path(__file__).resolve().parent.parent.parent
SOURCE = REPO / "docs" / "agents" / "agent-instructions.md"

TARGETS = {
    "AGENTS.md": {
        "header": "# MMDEP — Agent Instructions (Codex)\n\n"
        "Generated from `docs/agents/agent-instructions.md`. Do not edit directly.\n",
    },
    ".github/copilot-instructions.md": {
        "header": "# MMDEP — Copilot Instructions\n\nGenerated from `docs/agents/agent-instructions.md`. Do not edit directly.\n",
    },
    "GEMINI.md": {
        "header": "# MMDEP — Gemini Instructions\n\nGenerated from `docs/agents/agent-instructions.md`. Do not edit directly.\n",
    },
    "docs/agents/project-instructions.txt": {
        "header": "MMDEP — Project Instructions (Claude Projects / ChatGPT Projects)\n\n"
        "Generated from docs/agents/agent-instructions.md. Do not edit directly.\n",
    },
}


def extract_blocks(source_text: str) -> dict[str, str]:
    blocks: dict[str, str] = {}
    lines = source_text.replace("\r\n", "\n").split("\n")
    current_name: str | None = None
    current_lines: list[str] = []
    for line in lines:
        if line.startswith("### BLOCK: "):
            if current_name is not None:
                blocks[current_name] = "\n".join(current_lines).strip()
            current_name = line[len("### BLOCK: ") :]
            current_lines = []
        elif line == "## END SHARED BLOCKS":
            if current_name is not None:
                blocks[current_name] = "\n".join(current_lines).strip()
            break
        elif current_name is not None:
            current_lines.append(line)
    return blocks


def _heading(block_name: str) -> str:
    return block_name.replace("-", " ").replace("_", " ").title()


def render(header: str, blocks: dict[str, str]) -> str:
    parts = [header, ""]
    for name, content in blocks.items():
        parts.append(f"## {_heading(name)}\n")
        parts.append(content)
        parts.append("")
    return "\n".join(parts) + "\n"


def generate(check: bool = False) -> bool:
    source_text = SOURCE.read_text(encoding="utf-8")
    blocks = extract_blocks(source_text)
    if not blocks:
        print(f"ERROR: no blocks found in {SOURCE}", file=sys.stderr)
        return False

    ok = True
    for rel_path, cfg in TARGETS.items():
        target = REPO / rel_path
        expected = render(cfg["header"], blocks)
        if check:
            if not target.exists():
                print(f"MISSING: {rel_path}")
                ok = False
            elif target.read_text(encoding="utf-8") != expected:
                print(f"STALE: {rel_path}")
                ok = False
            else:
                print(f"OK: {rel_path}")
        else:
            target.parent.mkdir(parents=True, exist_ok=True)
            target.write_text(expected, encoding="utf-8")
            print(f"wrote {rel_path}")
    return ok


if __name__ == "__main__":
    check_mode = "--check" in sys.argv
    if not generate(check=check_mode):
        sys.exit(1)
