"""Carga personas y sus autorizaciones en el registro de habeas data desde un CSV.

Uso (Python 3.9+, solo biblioteca estándar):
    export INTEGRATION_API_TOKEN=nxl_...
    export INTEGRATION_API_URL=http://localhost:4100/integration/v1   # opcional
    python send_batch.py [ruta/al/archivo.csv]   # por defecto ../people.csv

La Idempotency-Key se deriva del contenido de cada lote: volver a ejecutar el
script con el mismo archivo devuelve el resultado original (HTTP 200) sin
cargar nada de nuevo.
"""

import csv
import hashlib
import json
import os
import sys
import time
import urllib.error
import urllib.request
from pathlib import Path

API_URL = os.environ.get("INTEGRATION_API_URL", "http://localhost:4100/integration/v1").rstrip("/")
TOKEN = os.environ.get("INTEGRATION_API_TOKEN")
BATCH_SIZE = 1000
MAX_ATTEMPTS = 5


def request(method, path, body=None, headers=None):
    """Envía una solicitud y devuelve (status, cabeceras, JSON). Reintenta lo reintentable."""
    for attempt in range(1, MAX_ATTEMPTS + 1):
        req = urllib.request.Request(f"{API_URL}{path}", data=body, method=method)
        req.add_header("Authorization", f"Bearer {TOKEN}")
        if body is not None:
            req.add_header("Content-Type", "application/json")
        for name, value in (headers or {}).items():
            req.add_header(name, value)
        try:
            with urllib.request.urlopen(req, timeout=60) as res:
                return res.status, res.headers, json.load(res)
        except urllib.error.HTTPError as err:
            status, payload = err.code, json.loads(err.read() or b"{}")
            retryable = status in (409, 429) or status >= 500
            if not retryable or attempt == MAX_ATTEMPTS:
                error = payload.get("error", {})
                sys.exit(f"Error {status} {error.get('code')}: {error.get('message')}")
            wait = int(err.headers.get("Retry-After", 0)) or 2 ** (attempt - 1)
        except urllib.error.URLError as err:
            if attempt == MAX_ATTEMPTS:
                sys.exit(f"No se pudo conectar con la API: {err.reason}")
            wait = 2 ** (attempt - 1)
        print(f"  Reintento {attempt}/{MAX_ATTEMPTS - 1} en {wait} s…")
        time.sleep(wait)


def to_record(row):
    """Una fila del CSV → un registro de la API; los opcionales vacíos se omiten."""
    record = {"documentType": row["documentType"], "documentNumber": row["documentNumber"], "fullName": row["fullName"]}
    for field in ("email", "phone"):
        if row.get(field):
            record[field] = row[field]
    authorization = {"authorizedOn": row["authorizedOn"], "channel": row["channel"]}
    for field in ("policyVersion", "evidenceReference"):
        if row.get(field):
            authorization[field] = row[field]
    record["authorization"] = authorization
    return record


def main():
    if not TOKEN:
        sys.exit("Defina INTEGRATION_API_TOKEN con el token creado en el portal (Integraciones).")
    csv_path = Path(sys.argv[1]) if len(sys.argv) > 1 else Path(__file__).resolve().parent.parent / "people.csv"

    _, _, ping = request("GET", "/ping")
    print(f"Conectado a {ping['tenant']['name']} · permisos: {', '.join(ping['token']['scopes'])}")

    with open(csv_path, newline="", encoding="utf-8") as f:
        records = [to_record(row) for row in csv.DictReader(f)]

    for start in range(0, len(records), BATCH_SIZE):
        body = json.dumps(
            {"externalReference": csv_path.name, "records": records[start : start + BATCH_SIZE]},
            ensure_ascii=False,
            separators=(",", ":"),
        ).encode("utf-8")
        key = "personas-" + hashlib.sha256(body).hexdigest()[:32]
        status, headers, batch = request("POST", "/authorizations", body, {"Idempotency-Key": key})

        replayed = headers.get("Idempotent-Replayed") == "true"
        print(f"\nLote {batch['id']} · HTTP {status}{' (reintento: resultado original)' if replayed else ''}")
        print("  " + " · ".join(f"{name}: {count}" for name, count in batch["counts"].items()))
        for result in batch["records"]:
            if result["status"] == "rejected":
                line = start + result["index"] + 2  # la línea 1 es el encabezado
                issues = ", ".join(f"{i['field']} ({i['code']})" for i in result["issues"])
                print(f"  Rechazado · línea {line} del CSV: {issues}")


if __name__ == "__main__":
    main()
