#!/usr/bin/env python3
"""Generate docs/ACHIEVEMENTS.md from the builtin catalog in the SQL script.

The SQL install script is the single source of truth for the catalog; run
this after changing it:  python3 docs/gen_achievements.py > docs/ACHIEVEMENTS.md

The script read is the one of default_version in pg_achievements.control,
so a new version needs no change here.
"""
import re
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent


def install_script() -> Path:
    """The install script of default_version: what CREATE EXTENSION runs."""
    control = (ROOT / "pg_achievements.control").read_text()
    match = re.search(r"^default_version\s*=\s*'([^']+)'", control, re.M)
    if match is None:
        sys.exit("default_version not found in pg_achievements.control")
    return ROOT / "sql" / f"pg_achievements--{match.group(1)}.sql"


SQL = install_script()

ROW = re.compile(
    r"^\('(?P<code>[a-z0-9_]+)',\s*'(?P<title>(?:[^']|'')*)',\s*"
    r"'(?P<desc>(?:[^']|'')*)',\s*'(?P<tier>\w+)',\s*(?P<points>\d+),\s*"
    r"(?P<secret>true|false),\s*'(?P<key>[^']+)',\s*(?P<threshold>\d+)\)"
)

TIERS = [
    ("bronze", "Bronze", "first steps"),
    ("silver", "Silver", "mastering PostgreSQL features"),
    ("gold", "Gold", "risky, rare and legendary events"),
    ("platinum", "Platinum", "collect them all"),
]


def condition(key, threshold):
    if key == "meta:all":
        return "every other builtin achievement"
    if key.startswith("meta:tier:"):
        return f"every builtin {key.split(':')[2]} achievement"
    return f"`{key}` ≥ {threshold}"


def main():
    rows = [m.groupdict() for m in map(ROW.match, SQL.read_text().splitlines()) if m]
    out = [
        "# Achievements",
        "",
        "<!-- generated by docs/gen_achievements.py, do not edit by hand -->",
        "",
        f"pg_achievements ships {len(rows)} builtin achievements. Each one is "
        "unlocked when a counter of the role reaches the threshold; the counters "
        "are described in the [README](../README.md#counters). Secret "
        "achievements show `???` instead of the description in "
        "`achievements.progress` until they are unlocked.",
        "",
    ]
    for tier, name, blurb in TIERS:
        tier_rows = [r for r in rows if r["tier"] == tier]
        points = tier_rows[0]["points"] if tier_rows else "?"
        out += [f"## {name} — {points} points, {blurb}", "",
                "| Code | Title | Description | Condition |",
                "| --- | --- | --- | --- |"]
        for r in tier_rows:
            title = r["title"].replace("''", "'")
            desc = r["desc"].replace("''", "'")
            secret = " 🔒" if r["secret"] == "true" else ""
            out.append(f"| `{r['code']}` | {title}{secret} | {desc} | "
                       f"{condition(r['key'], r['threshold'])} |")
        out.append("")
    out += ["🔒 — secret achievement.", ""]
    sys.stdout.write("\n".join(out))


if __name__ == "__main__":
    main()
