#!/usr/bin/env python3
"""
sync-profile.py — ambil preferensi user + selected_portal (portal yang diizinkan)
dari BE (GET /v1/agent/user-profile) lalu simpan ke user-profile.json.

Dipanggil saat provisioning mesin & sebelum tiap daily run (run-daily.sh),
jadi preferensi selalu fresh (user ubah → run berikutnya dapat versi baru).

Config: agent-config.env di folder yang sama (BE_API_URL, BE_INTERNAL_TOKEN, USER_ID).

Pemakaian:
  python3 sync-profile.py
"""
import json
import os
import sys
import urllib.error
import urllib.request
from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent
CONFIG_FILE = BASE_DIR / "agent-config.env"
PROFILE_FILE = BASE_DIR / "user-profile.json"


def load_config() -> dict:
    cfg = {
        "BE_API_URL": os.environ.get("BE_API_URL", ""),
        "BE_INTERNAL_TOKEN": os.environ.get("BE_INTERNAL_TOKEN", ""),
        "USER_ID": os.environ.get("USER_ID", ""),
    }
    if CONFIG_FILE.exists():
        for line in CONFIG_FILE.read_text().splitlines():
            line = line.strip()
            if not line or line.startswith("#") or "=" not in line:
                continue
            k, _, v = line.partition("=")
            k, v = k.strip(), v.strip()
            if k in cfg and not cfg[k]:
                cfg[k] = v
    missing = [k for k, v in cfg.items() if not v]
    if missing:
        print(f"ERROR: config kurang: {', '.join(missing)} (isi {CONFIG_FILE})", file=sys.stderr)
        sys.exit(2)
    return cfg


def main():
    cfg = load_config()
    url = cfg["BE_API_URL"].rstrip("/") + f"/v1/agent/user-profile?user_id={cfg['USER_ID']}"
    req = urllib.request.Request(
        url,
        method="GET",
        headers={"X-Internal-Token": cfg["BE_INTERNAL_TOKEN"]},
    )
    try:
        with urllib.request.urlopen(req, timeout=20) as resp:
            data = json.loads(resp.read().decode() or "{}")
            # BE produksi membungkus respons di {"data": {...}}
            if isinstance(data, dict) and "data" in data and isinstance(data["data"], dict):
                data = data["data"]
    except urllib.error.HTTPError as e:
        if e.code == 404:
            print("WARN: profil belum ada di BE (404) — simpan profil kosong", file=sys.stderr)
            data = {"profile": {}, "selected_portal": []}
        else:
            print(f"ERROR: HTTP {e.code}: {e.read().decode()[:200]}", file=sys.stderr)
            sys.exit(1)
    except Exception as e:
        print(f"ERROR: {e}", file=sys.stderr)
        sys.exit(1)

    PROFILE_FILE.write_text(json.dumps(data, indent=2, ensure_ascii=False) + "\n")
    n_portals = len(data.get("selected_portal", []))
    keys = list(data.get("profile", {}).keys())
    print(f"OK: user-profile.json tersimpan (selected_portal: {n_portals}, profile: {keys})")


if __name__ == "__main__":
    main()
