#!/usr/bin/env python3
import json
from pathlib import Path

HERE = Path(__file__).resolve().parent
CATALOG = HERE / "catalog.json"
OUT = HERE / "README.md"

with CATALOG.open("r", encoding="utf-8") as f:
    data = json.load(f)

lines = [
    "# Project scripts",
    "",
    "This file is generated from `scripts/catalog.json`.",
    "",
    "## How to register a new script",
    "",
    "1) Add an entry in `scripts/catalog.json` under `scripts`.",
    "2) Run:",
    "",
    "```bash",
    str(HERE / "catalog_to_md.py"),
    "```",
    "",
    "---",
    "",
]

docs = data.get("docs", [])
if docs:
    lines.append("## Docs")
    lines.append("")
    for d in docs:
        lines.append(f"### {d.get('name')}")
        lines.append("")
        if d.get("purpose"):
            lines.append(d["purpose"])
            lines.append("")
        if d.get("path"):
            lines.append(f"Path: `{d['path']}`")
            lines.append("")
    lines.append("---")
    lines.append("")

for s in data.get("scripts", []):
    lines.append(f"## {s.get('name')}")
    lines.append("")
    lines.append(s.get("purpose", ""))
    lines.append("")
    if s.get("path"):
        lines.append(f"Path: `{s['path']}`")
        lines.append("")
    if s.get("example"):
        lines.append("Example:")
        lines.append("")
        lines.append("```bash")
        lines.append(s["example"])
        lines.append("```")
        lines.append("")
    if s.get("inputs"):
        lines.append("Inputs:")
        for i in s["inputs"]:
            lines.append(f"- {i}")
        lines.append("")
    if s.get("outputs"):
        lines.append("Outputs:")
        for o in s["outputs"]:
            lines.append(f"- {o}")
        lines.append("")
    if s.get("dependencies"):
        lines.append("Dependencies:")
        for d in s["dependencies"]:
            lines.append(f"- {d}")
        lines.append("")
    if s.get("tags"):
        lines.append("Tags: " + ", ".join(s["tags"]))
        lines.append("")

OUT.write_text("\n".join(lines).rstrip() + "\n", encoding="utf-8")
