# export_cartera.py  —  Exporta TODA la tabla cartera_junta de Supabase a Excel/CSV.
# Ejecutar dentro de backend/:  python export_cartera.py
import os, csv, requests
from dotenv import load_dotenv
load_dotenv()

URL = os.getenv("CARTERA_URL") or os.getenv("SUPABASE_PAUTA_URL", "")
KEY = os.getenv("CARTERA_KEY") or os.getenv("SUPABASE_PAUTA_KEY", "")
TABLA = os.getenv("SUPABASE_TABLA_CARTERA", "cartera_junta")
HEAD = {"apikey": KEY, "Authorization": f"Bearer {KEY}"}

def traer_todo():
    filas, paso, desde = [], 1000, 0
    while True:
        r = requests.get(f"{URL}/rest/v1/{TABLA}",
                         params={"select": "*", "offset": str(desde), "limit": str(paso)},
                         headers=HEAD, timeout=120)
        r.raise_for_status()
        data = r.json()
        if not data:
            break
        filas.extend(data)
        print(f"  descargadas {len(filas)} filas...")
        if len(data) < paso:
            break
        desde += paso
    return filas

print(f"Descargando '{TABLA}' de Supabase...")
filas = traer_todo()
print(f"Total: {len(filas)} filas")

if not filas:
    print("Sin datos. Revisa CARTERA_URL / CARTERA_KEY en .env")
    raise SystemExit

# columnas = union de todas las claves, en orden de la primera fila
cols = list(filas[0].keys())
for f in filas:
    for k in f.keys():
        if k not in cols:
            cols.append(k)

# 1) CSV siempre
csv_path = "cartera_junta_export.csv"
with open(csv_path, "w", newline="", encoding="utf-8-sig") as fout:
    w = csv.DictWriter(fout, fieldnames=cols)
    w.writeheader()
    for f in filas:
        w.writerow({c: f.get(c, "") for c in cols})
print(f"CSV generado: {csv_path}")

# 2) Excel si openpyxl esta disponible
try:
    from openpyxl import Workbook
    wb = Workbook(); ws = wb.active; ws.title = "cartera_junta"
    ws.append(cols)
    for f in filas:
        ws.append([f.get(c, "") for c in cols])
    xlsx_path = "cartera_junta_export.xlsx"
    wb.save(xlsx_path)
    print(f"Excel generado: {xlsx_path}")
except ImportError:
    print("(openpyxl no instalado -> solo CSV. Para Excel: pip install openpyxl)")
