import os, csv
import requests
from dotenv import load_dotenv
from collections import Counter

load_dotenv()

url = os.getenv("CARTERA_URL") or os.getenv("SUPABASE_PAUTA_URL", "")
key = os.getenv("CARTERA_KEY") or os.getenv("SUPABASE_PAUTA_KEY", "")
t   = os.getenv("SUPABASE_TABLA_CARTERA", "cartera_junta")

assert url and key, "Falta CARTERA_URL / CARTERA_KEY en .env"

sel  = "telefono,sede,programa,fecha_creada,asesor,es_origen,canal,origen_base"
paso, desde = 1000, 0
out = []
while True:
    hdr = {"apikey": key, "Authorization": f"Bearer {key}",
           "Range-Unit": "items", "Range": f"{desde}-{desde + paso - 1}"}
    r = requests.get(f"{url}/rest/v1/{t}",
                     params={"select": sel, "order": "id.asc"},
                     headers=hdr, timeout=60)
    r.raise_for_status()
    data = r.json()
    if not data:
        break                       # parar SOLO cuando devuelve 0
    out.extend(data)
    desde += len(data)
    print(f"  descargadas: {desde}", end="\r")

print(f"\n\nTOTAL filas descargadas: {len(out)}")

ori = Counter(str(x.get("es_origen") or "").strip().upper() for x in out)
print("es_origen:", ori.most_common(5))

ob = Counter(str(x.get("origen_base") or "").strip().upper() for x in out)
print("origen_base:", ob.most_common(5))

sede = Counter(str(x.get("sede") or "").strip().upper() for x in out)
print("por SEDE:", sede.most_common(10))

# Exporta a CSV para comparar en Excel
salida = "cartera_bajada.csv"
with open(salida, "w", newline="", encoding="utf-8-sig") as f:
    w = csv.DictWriter(f, fieldnames=sel.split(","))
    w.writeheader()
    for x in out:
        w.writerow({k: x.get(k, "") for k in sel.split(",")})
print(f"\nExportado a: {salida}")
