#!/usr/bin/env python3
"""
Export completo de la base BewPro vieja (app24JOjh8oJK16rw) a JSON local.
Uso: python3 scripts/airtable-export-old.py
"""

import json
import urllib.request
import urllib.parse
import os
import time

TOKEN = "patUFXGCZ4lEcCQDx.88ed15dafa2a89c89d70b405bb86f97fdb9e097737ed5e5b0b3c33b252de51cb"
OLD_BASE = "app24JOjh8oJK16rw"
OUT_DIR = "docs/airtable-backup/bewpro-old"

TABLES = {
    "modules":          "tbll7vdvr425A5Vhv",
    "projects":         "tblbBxyw2EE07zwvv",
    "clients":          "tblPVSGvIbAN55p7P",
    "alias-dictionary": "tblb8PLRSun0ylSL1",
    "products":         "tblucEFuAU8hMosXa",
    "subscriptions":    "tblB7rDmBDw24bJTO",
    "users":            "tblgtK9QaZH87YuO5",
    "templates":        "tblqhpkU0z2FhloUm",
    "industries":       "tblile6pEBsEKFEIV",
    "automation":       "tblRlyyzeD2wIsTDi",
    "imported":         "tblOuQuc0xXtPZnnA",
}

def fetch_all(table_id):
    records = []
    offset = None
    while True:
        url = f"https://api.airtable.com/v0/{OLD_BASE}/{table_id}?maxRecords=200"
        if offset:
            url += f"&offset={urllib.parse.quote(offset)}"
        req = urllib.request.Request(url, headers={"Authorization": f"Bearer {TOKEN}"})
        with urllib.request.urlopen(req) as resp:
            data = json.loads(resp.read())
        records.extend(data.get("records", []))
        offset = data.get("offset")
        if not offset:
            break
        time.sleep(0.2)
    return records

os.makedirs(OUT_DIR, exist_ok=True)

all_data = {}
for name, table_id in TABLES.items():
    print(f"  Exportando {name}...", end=" ", flush=True)
    try:
        records = fetch_all(table_id)
        all_data[name] = records
        path = os.path.join(OUT_DIR, f"{name}.json")
        with open(path, "w", encoding="utf-8") as f:
            json.dump(records, f, ensure_ascii=False, indent=2)
        print(f"{len(records)} registros → {path}")
    except Exception as e:
        print(f"ERROR: {e}")

# Dump completo
with open(os.path.join(OUT_DIR, "all-tables.json"), "w", encoding="utf-8") as f:
    json.dump(all_data, f, ensure_ascii=False, indent=2)

print(f"\n✅ Backup completo en {OUT_DIR}/")
print(f"   Total registros: {sum(len(v) for v in all_data.values())}")
