#!/usr/bin/env python3
"""
Enriquece los Module records en Airtable 2.0 con Detailed Description
y Demo_URL de la base vieja.
Uso: python3 scripts/migrate-modules.py [--dry-run]
"""

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

TOKEN = "patUFXGCZ4lEcCQDx.88ed15dafa2a89c89d70b405bb86f97fdb9e097737ed5e5b0b3c33b252de51cb"
NEW_BASE = "appRxvpzqCmNsw2JN"
MODULES_TABLE = "tblhUsIJi0iba6DEN"

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

# Mapping nombre old → slug 2.0
NAME_TO_SLUG = {
    "References":             "references",
    "FAQs":                   "faqs",
    "Team":                   "team",
    "Blog":                   "blog",
    "Gallery":                "gallery",
    "Products":               "products",
    "Services":               "services",
    "Projects":               "projects",
    "BP Base system":         "bp-base",
    "News":                   "news",
    "Tokko API Integration":  "tokko",
    "Testimonials":           "testimonials",
}

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_patch(table, record_id, fields):
    url = f"https://api.airtable.com/v0/{NEW_BASE}/{table}/{record_id}"
    data = json.dumps({"fields": fields}).encode()
    req = urllib.request.Request(
        url, data=data, method="PATCH",
        headers={"Authorization": f"Bearer {TOKEN}", "Content-Type": "application/json"}
    )
    with urllib.request.urlopen(req) as resp:
        return json.loads(resp.read())

# Load old modules from backup
with open("docs/airtable-backup/bewpro-old/modules.json") as f:
    old_modules = json.load(f)

# Build map slug → old data
old_by_slug = {}
for r in old_modules:
    f = r.get("fields", {})
    name = f.get("Name", "")
    slug = NAME_TO_SLUG.get(name)
    if slug:
        old_by_slug[slug] = f

# Fetch 2.0 modules
data = api_get(f"https://api.airtable.com/v0/{NEW_BASE}/{MODULES_TABLE}?maxRecords=50")
new_modules = data.get("records", [])

print(f"{'DRY RUN — ' if DRY_RUN else ''}Migrando module descriptions ({len(new_modules)} módulos en 2.0)\n")

updated = 0
for rec in new_modules:
    slug = rec.get("fields", {}).get("Slug", "")
    if not slug or slug not in old_by_slug:
        print(f"  SKIP {slug} (no match en old base)")
        continue

    old = old_by_slug[slug]
    current = rec.get("fields", {})

    updates = {}

    # Actualizar Description si old tiene Detailed Description más larga
    old_desc = old.get("Detailed Description", "").strip()
    curr_desc = current.get("Description", "").strip()
    if old_desc and len(old_desc) > len(curr_desc):
        updates["Description"] = old_desc

    # Actualizar Demo_URL si está vacío en 2.0
    old_url = old.get("Demo URL", "").strip()
    curr_url = current.get("Demo_URL", "").strip()
    if old_url and not curr_url:
        # Convert localhost URL to a generic pattern
        updates["Demo_URL"] = old_url.replace("http://127.0.0.1:8000", "https://bewpro.com")

    if not updates:
        print(f"  OK   {slug} — ya está completo")
        continue

    print(f"  UPD  {slug} — actualizando: {list(updates.keys())}")
    if not DRY_RUN:
        api_patch(MODULES_TABLE, rec["id"], updates)
        time.sleep(0.2)
    updated += 1

print(f"\n{'[DRY RUN] Hubiera actualizado' if DRY_RUN else 'Actualizados'}: {updated} módulos")
