#!/usr/bin/env python3
"""
Migra los billing contacts de la base vieja a Contacts en Airtable 2.0.
- Lee docs/airtable-backup/bewpro-old/clients.json
- Para cada cliente con Billing Email, busca si ya existe en 2.0 por email
- Si no existe, lo crea con: Name, Email, Role=Client Owner, Client_Company, Notes

Uso: python3 scripts/migrate-contacts.py [--dry-run]
"""

import json, sys, time, urllib.request, urllib.parse

DRY_RUN = "--dry-run" in sys.argv

TOKEN    = "patUFXGCZ4lEcCQDx.88ed15dafa2a89c89d70b405bb86f97fdb9e097737ed5e5b0b3c33b252de51cb"
NEW_BASE = "appRxvpzqCmNsw2JN"
CONTACTS = "tblmGnOiTXxjzR4dE"

def api_get(url):
    req = urllib.request.Request(url, headers={"Authorization": f"Bearer {TOKEN}"})
    with urllib.request.urlopen(req) as resp:
        return json.loads(resp.read())

def api_post(table, records_data):
    url = f"https://api.airtable.com/v0/{NEW_BASE}/{table}"
    body = json.dumps({"records": records_data}).encode()
    req = urllib.request.Request(url, data=body, method="POST",
        headers={"Authorization": f"Bearer {TOKEN}", "Content-Type": "application/json"})
    with urllib.request.urlopen(req) as resp:
        return json.loads(resp.read())

# ── Load old clients ──────────────────────────────────────────
with open("docs/airtable-backup/bewpro-old/clients.json") as f:
    old_clients = json.load(f)

# Extract clients with billing email
source_contacts = []
for r in old_clients:
    fields = r.get("fields", {})
    billing = fields.get("Billing Email", "").strip()
    name    = fields.get("Client Name", "").strip()
    country = fields.get("Country", "").strip()
    status  = fields.get("Status", "").strip()
    if billing:
        source_contacts.append({
            "email":   billing,
            "name":    name or billing.split("@")[0].replace(".", " ").title(),
            "company": name,
            "country": country,
            "status":  status,
        })

print(f"Contacts a migrar desde base vieja: {len(source_contacts)}")

# ── Fetch existing Contacts in 2.0 ───────────────────────────
print("Fetching Contacts en 2.0...")
existing_emails = set()
offset = None
while True:
    url = f"https://api.airtable.com/v0/{NEW_BASE}/{CONTACTS}?maxRecords=200"
    if offset:
        url += f"&offset={urllib.parse.quote(offset)}"
    data = api_get(url)
    for rec in data.get("records", []):
        email = rec.get("fields", {}).get("Email", "").strip().lower()
        if email:
            existing_emails.add(email)
    offset = data.get("offset")
    if not offset:
        break

print(f"  → {len(existing_emails)} contacts ya en 2.0")

# ── Find missing ──────────────────────────────────────────────
missing = [c for c in source_contacts if c["email"].lower() not in existing_emails]
print(f"\nNuevos a crear: {len(missing)}")

if DRY_RUN:
    print("\nDRY RUN:")
    for c in missing:
        print(f"  {c['email']} → {c['name']} ({c['company']}, {c['country']}, {c['status']})")
    sys.exit(0)

if not missing:
    print("Nada que crear.")
    sys.exit(0)

# ── Create in batches of 10 ───────────────────────────────────
def batch(lst, n):
    for i in range(0, len(lst), n):
        yield lst[i:i+n]

created = 0
failed = []

for chunk in batch(missing, 10):
    records = []
    for c in chunk:
        notes_parts = []
        if c["country"]:
            notes_parts.append(f"País: {c['country']}")
        if c["status"]:
            notes_parts.append(f"Status viejo: {c['status']}")
        notes_parts.append("Migrado desde BewPro base (2026-03)")

        fields = {
            "Name":           c["name"],
            "Email":          c["email"],
            "Role":           "Client Owner",
            "Client_Company": c["company"] if c["company"] else c["name"],
            "Notes":          " · ".join(notes_parts),
        }
        records.append({"fields": fields})

    try:
        result = api_post(CONTACTS, records)
        created += len(result.get("records", []))
        for rec in result.get("records", []):
            print(f"  ✓ {rec['fields'].get('Email', '')} — {rec['fields'].get('Name', '')}")
        time.sleep(0.3)
    except Exception as e:
        print(f"  ERROR batch: {e}")
        failed.extend([c["email"] for c in chunk])

print(f"\n✅ Done! Contacts creados: {created}")
if failed:
    print(f"   Fallidos: {failed}")
