#!/usr/bin/env python
"""Snapshot normalise des reponses /api/v1/metadata/* (recette refonte chaps).

Usage : python snapshot.py <base_url> <api_key> <out_dir>
Capture chaque module actif x (sans role, admin, viewer) x (fr, en), corps JSON
trie par cles, champ volatile `locale` retire. Le diff avant/apres se fait avec
un simple `diff -ru`.
"""
import json
import sys
import urllib.request
from pathlib import Path

base, key, out = sys.argv[1], sys.argv[2], Path(sys.argv[3])
out.mkdir(parents=True, exist_ok=True)


def get(url):
    req = urllib.request.Request(url, headers={"X-API-KEY": key, "Accept": "application/json"})
    with urllib.request.urlopen(req, timeout=60) as r:
        return json.loads(r.read().decode("utf-8"))


mods = get(f"{base}/api/v1/admin/modules?size=1000")
rows = mods.get("data", mods) or []
names = sorted({m["name"] for m in rows if m.get("is_active") == 1 and m.get("is_deleted") != 1})
if not names:
    sys.exit("aucun module actif")

count = 0
for module in names:
    for role in ("", "admin", "viewer"):
        for lang in ("fr", "en"):
            url = f"{base}/api/v1/metadata/{module}?lang={lang}"
            if role:
                url += f"&identity_role={role}"
            try:
                body = get(url)
            except Exception as exc:  # noqa: BLE001
                print(f"  ! echec {url}: {exc}", file=sys.stderr)
                continue
            body.pop("locale", None)
            suffix = role or "_norole"
            (out / f"{module}__{suffix}__{lang}.json").write_text(
                json.dumps(body, sort_keys=True, ensure_ascii=False, indent=1),
                encoding="utf-8",
            )
            count += 1

print(f"{count} reponse(s) capturee(s) dans {out}")
