#!/usr/bin/env python3
"""
Importa core-products-copy.json a Airtable 2.0 Products Copy.
- Solo crea registros faltantes (nunca sobreescribe los existentes)

Uso: python3 scripts/import-core-copy.py [--dry-run]
"""

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

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

TOKEN    = "patUFXGCZ4lEcCQDx.88ed15dafa2a89c89d70b405bb86f97fdb9e097737ed5e5b0b3c33b252de51cb"
NEW_BASE = "appRxvpzqCmNsw2JN"
TABLE_ID = "tbl4c7e3IA9vtnBkh"  # Products Copy

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(records_data):
    url = f"https://api.airtable.com/v0/{NEW_BASE}/{TABLE_ID}"
    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 source data
with open("database/seeders/products/core-products-copy.json") as f:
    SOURCE = json.load(f)

# Fetch existing slugs in Airtable
print("Fetching Products Copy en Airtable...")
existing_slugs = set()
offset = None
while True:
    url = f"https://api.airtable.com/v0/{NEW_BASE}/{TABLE_ID}?maxRecords=200"
    if offset:
        url += f"&offset={urllib.parse.quote(offset)}"
    data = api_get(url)
    for r in data.get("records", []):
        slug = r.get("fields", {}).get("Product_Slug", "").strip()
        if slug:
            existing_slugs.add(slug)
    offset = data.get("offset")
    if not offset:
        break

print(f"  → {len(existing_slugs)} registros existentes: {sorted(existing_slugs)}")

missing = {slug: data for slug, data in SOURCE.items() if slug not in existing_slugs}
print(f"  → {len(missing)} a crear: {sorted(missing.keys())}")

if DRY_RUN:
    print("\nDRY RUN — preview:")
    for slug, data in missing.items():
        print(f"\n  [{slug}]")
        print(f"    Tagline:  {data.get('Tagline','')}")
        print(f"    Headline: {data.get('Headline','')}")
        print(f"    Persona:  {data.get('Target_Persona','')[:80]}...")
    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]

items = list(missing.items())
created = 0
failed = []

print(f"\nCreando {len(missing)} registros en Products Copy...")
for chunk in batch(items, 10):
    records = []
    for slug, data in chunk:
        fields = {
            "Product_Slug":   slug,
            "Tagline":        data.get("Tagline", ""),
            "Headline":       data.get("Headline", ""),
            "Target_Persona": data.get("Target_Persona", ""),
            "Pain_Points":    data.get("Pain_Points", ""),
            "Value_Props":    data.get("Value_Props", ""),
            "CTA_Primary":    data.get("CTA_Primary", ""),
            "CTA_Secondary":  data.get("CTA_Secondary", "Contactar"),
            "Copy_Status":    "Draft",
        }
        records.append({"fields": fields})

    try:
        result = api_post(records)
        created += len(result.get("records", []))
        for rec in result.get("records", []):
            s = rec["fields"].get("Product_Slug", "")
            h = rec["fields"].get("Headline", "")
            print(f"  ✓ {s:25s} → {h}")
        time.sleep(0.3)
    except Exception as e:
        print(f"  ERROR: {e}")
        failed.extend([s for s, _ in chunk])

total = len(existing_slugs) + created
print(f"\n✅ Done!")
print(f"   Products Copy: {len(existing_slugs)} → {total} (+{created})")
if failed:
    print(f"   Fallidos: {failed}")
