#!/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"),
    "```",
    "",
    "---",
    "",
]

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")
