#!/usr/bin/env python3
"""
Render instancias.json a partir de instancias.json.template + .env files.

Uso:
    python3 render_instancias.py

Le placeholders {{VAR_NAME}} do template e substitui pelos valores dos
/opt/mia/config/*.env correspondentes. Escreve instancias.json com chmod 600.

Rode este script sempre que:
- Atualizar o template
- Rotacionar tokens nos .env files

Motivo: instancias.json fica no .gitignore (contem segredos renderizados);
o template + este script vao pro git.
"""
import json
import os
import re
import stat
import sys
from pathlib import Path

BASE = Path(__file__).resolve().parent
TEMPLATE = BASE / "instancias.json.template"
OUTPUT = BASE / "instancias.json"

ENV_FILES = [
    "/opt/mia/config/linkia_px3.env",
    "/opt/mia/config/linkia_climb.env",
    "/opt/mia/config/linkia_borrello.env",
    "/opt/mia/config/linkia_sweet_angels.env",
]


def load_env(path):
    data = {}
    p = Path(path)
    if not p.exists():
        return data
    with p.open() as f:
        for line in f:
            line = line.strip()
            if not line or line.startswith("#") or "=" not in line:
                continue
            k, v = line.split("=", 1)
            data[k.strip()] = v.strip().strip('"').strip("'")
    return data


def main():
    if not TEMPLATE.exists():
        print(f"ERRO: template nao encontrado em {TEMPLATE}", file=sys.stderr)
        sys.exit(1)

    env = {}
    for path in ENV_FILES:
        env.update(load_env(path))
    # Merge com os.environ (env vars ganham prioridade)
    env.update({k: v for k, v in os.environ.items() if k in env or k.startswith("LINKIA_") or k.startswith("CLIMB_") or k.startswith("PX3_")})

    src = TEMPLATE.read_text()
    placeholders = set(re.findall(r"\{\{([A-Z0-9_]+)\}\}", src))

    missing = []
    for ph in placeholders:
        if ph not in env or not env[ph]:
            missing.append(ph)
    if missing:
        print(f"ERRO: placeholders sem valor: {missing}", file=sys.stderr)
        sys.exit(2)

    rendered = src
    for ph in placeholders:
        rendered = rendered.replace("{{" + ph + "}}", env[ph])

    # Valida JSON
    try:
        json.loads(rendered)
    except json.JSONDecodeError as e:
        print(f"ERRO: JSON invalido apos render: {e}", file=sys.stderr)
        sys.exit(3)

    OUTPUT.write_text(rendered)
    os.chmod(OUTPUT, stat.S_IRUSR | stat.S_IWUSR)  # 600
    print(f"OK: {OUTPUT} renderizado ({len(placeholders)} placeholders resolvidos, chmod 600)")


if __name__ == "__main__":
    main()
