#!/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
"""
import re
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
SQL = ROOT / "sql" / "pg_achievements--1.0.sql"

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 and rare events"),
    ("platinum", "Platinum", "the stuff of legends"),
]


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