#!/usr/bin/env python3
"""TheBestPlanner Notion OS 2027 ULTIMATE — Official Multi-Column Notion API Architect.

Zero external dependencies (100% Python 3 standard library).
Builds a world-class, zero-emoji, multi-column Notion workspace across ALL 7 luxury visual themes:
  - 1 Magazine-Grade 3-Column Command Hub with CDN HD Cover (1500x400), Custom 512px Icon,
    Clickable 5-Hub Navigation Panel, ADHD Energy/Dopamine & Zero-Guilt Brain Dump Callouts,
    3-Column Editorial Vision Board Gallery, KPI Strip, Quote Card & ALL 5 LIVE EMBEDDED WIDGETS.
  - 5 Dedicated Sub-Hubs (each with bespoke cover & minimalist PNG icon — zero clutter!).
  - 18 Interconnected Relational Databases with real Relation, Rollup & Formula 2.0 visual bars.

CLI Usage:
  python3 notion_ultimate_architect.py --theme cobalt --token ntn_xxx --page-url "https://notion.so/..."
  python3 notion_ultimate_architect.py --theme all --dry-run
"""

from __future__ import annotations

import argparse
import json
import re
import ssl
import sys
import time
import urllib.error
import urllib.request
from typing import Any, Callable

NOTION_API = "https://api.notion.com/v1"
NOTION_VERSION = "2022-06-28"
CDN_BASE = "https://improbearsia.github.io/thebestplanner-site/assets/notion_hd"
WIDGETS_BASE = "https://improbearsia.github.io/thebestplanner-site/widgets"

THEMES: dict[str, dict[str, str]] = {
    "cobalt": {
        "num": "01",
        "name": "Cobalt Ejecutivo",
        "tagline": "Claridad Suiza · Azul Profundo & Naranja Acción",
        "quote": "«La claridad estratégica convierte el caos diario en progreso compuesto.»",
        "callout": "blue_background",
        "callout_alt": "gray_background",
        "callout_focus": "orange_background",
    },
    "midnight": {
        "num": "02",
        "name": "Midnight OLED",
        "tagline": "Modo Nocturno · Obsidiana Pura & Ámbar Dorado",
        "quote": "«El enfoque profundo es la ventaja silenciosa de quienes construyen lo extraordinario.»",
        "callout": "gray_background",
        "callout_alt": "blue_background",
        "callout_focus": "orange_background",
    },
    "blush": {
        "num": "03",
        "name": "Rosa Pastel Aesthetic",
        "tagline": "Acuarela Peonías · 12 Tonos Pastel & Vino Suave",
        "quote": "«Avanza con calma, diseña tu vida con intención y celebra cada pequeño paso.»",
        "callout": "pink_background",
        "callout_alt": "purple_background",
        "callout_focus": "red_background",
    },
    "beige": {
        "num": "04",
        "name": "Aesthetic Beige & Latte",
        "tagline": "Editorial Minimalista · Lino Cálido & Terracota",
        "quote": "«Menos ruido, más presencia: el verdadero lujo es ser dueño de tu propio tiempo.»",
        "callout": "brown_background",
        "callout_alt": "orange_background",
        "callout_focus": "yellow_background",
    },
    "rainbow": {
        "num": "05",
        "name": "Clásico Multicolor",
        "tagline": "12 Meses Arcoíris · Energía Cromática & Orden",
        "quote": "«Cada mes es un lienzo nuevo para crear hábitos que transforman tu año.»",
        "callout": "orange_background",
        "callout_alt": "blue_background",
        "callout_focus": "purple_background",
    },
    "paper": {
        "num": "06",
        "name": "Papel Algodón & Salvia",
        "tagline": "Grabado Botánico · Verde Salvia & Crema Algodón",
        "quote": "«Lo que escribes con intención hoy se convierte en la realidad que vives mañana.»",
        "callout": "green_background",
        "callout_alt": "yellow_background",
        "callout_focus": "brown_background",
    },
    "moleskine": {
        "num": "07",
        "name": "Moleskine Clásico",
        "tagline": "Cuero Negro · Papel Marfil & Listón Carmesí",
        "quote": "«Las grandes obras nacen en páginas sencillas llenas de constancia diaria.»",
        "callout": "yellow_background",
        "callout_alt": "gray_background",
        "callout_focus": "red_background",
    },
}

MONTHLY_RITUALS_2027: list[tuple[str, str, str, str, str]] = [
    ("Enero", "Claridad & Visión", "La simplicidad es la máxima sofisticación.", "Leonardo da Vinci", "Definir Estrella Polar, 4 Pilares y Top 3 OKRs Q1"),
    ("Febrero", "Enfoque Profundo", "Haz menos cosas, pero con excelencia impecable.", "Greg McKeown", "Blindar 2 bloques diarios de Deep Work de 90 min"),
    ("Marzo", "Tracción Q1", "Lo que se mide con calma se mejora sin esfuerzo.", "Peter Drucker", "Cierre de sprint 12 semanas y auditoría de pendientes"),
    ("Abril", "Sistemas & Orden", "No subes al nivel de tus metas; caes al nivel de tus sistemas.", "James Clear", "Simplificar procesos y delegar 2 tareas repetitivas"),
    ("Mayo", "Rentabilidad", "El ingreso es vanidad, el margen es sanidad, el flujo es realidad.", "Principio FinOps", "Auditar suscripciones, margen neto y cartera clave"),
    ("Junio", "Balance Semestral", "Detenerse a recalibrar ahorra meses de esfuerzo equivocado.", "TheBestPlanner", "Evaluación de medio año y ajuste de Vision Board"),
    ("Julio", "Descanso & Energía", "Descansar a tiempo es una decisión estratégica de alto nivel.", "Cal Newport", "Recarga física, viaje consciente y detox digital"),
    ("Agosto", "Aceleración Q3", "La constancia silenciosa siempre vence al apuro.", "Filosofía TheBest", "Lanzar sprint Q3 con 3 rocas semanales medibles"),
    ("Septiembre", "Maestría", "Invertir en tu criterio paga dividendos toda la vida.", "Benjamin Franklin", "Completar 2 libros clave y actualizar Segundo Cerebro"),
    ("Octubre", "Ejecución Comercial", "Aporta claridad y servicio real antes de pedir resultados.", "Socio Estratégico", "Impulso comercial Q4 y seguimiento puntual de CRM"),
    ("Noviembre", "Gratitud & Cierre", "Agradecer lo construido abre espacio para lo siguiente.", "Séneca", "Balance anual, gratitud y presupuesto 2028"),
    ("Diciembre", "Legado 2028", "Diseña el próximo año desde la calma, no desde la urgencia.", "TheBestPlanner", "Celebrar victorias 2027 y trazar Visión 2028"),
]


def _rt(text: str, bold: bool = False, italic: bool = False, color: str = "default", url: str | None = None) -> list[dict[str, Any]]:
    text_obj: dict[str, Any] = {"content": text}
    if url:
        text_obj["link"] = {"url": url}
    return [{
        "type": "text",
        "text": text_obj,
        "annotations": {"bold": bold, "italic": italic, "color": color},
    }]


def _ext_icon(theme_key: str, icon_name: str) -> dict[str, Any]:
    return {"type": "external", "external": {"url": f"{CDN_BASE}/icons/{theme_key}/{icon_name}.png"}}


def _ext_cover(theme_key: str, filename: str) -> dict[str, Any]:
    return {"type": "external", "external": {"url": f"{CDN_BASE}/{theme_key}/{filename}"}}


def _img_block(url: str, caption: str = "") -> dict[str, Any]:
    img: dict[str, Any] = {"type": "external", "external": {"url": url}}
    if caption:
        img["caption"] = _rt(caption, italic=True, color="gray")
    return {"object": "block", "type": "image", "image": img}


def _embed_block(url: str) -> dict[str, Any]:
    return {"object": "block", "type": "embed", "embed": {"url": url}}


def _callout(theme_key: str, icon_name: str, text: str, bg_color: str, bold: bool = True, children: list[dict[str, Any]] | None = None) -> dict[str, Any]:
    body: dict[str, Any] = {
        "icon": _ext_icon(theme_key, icon_name),
        "color": bg_color,
        "rich_text": _rt(text, bold=bold),
    }
    if children:
        body["children"] = children
    return {"object": "block", "type": "callout", "callout": body}


def _h2(text: str) -> dict[str, Any]:
    return {"object": "block", "type": "heading_2", "heading_2": {"rich_text": _rt(text, bold=True)}}


def _h3(text: str) -> dict[str, Any]:
    return {"object": "block", "type": "heading_3", "heading_3": {"rich_text": _rt(text, bold=True)}}


def _p(text: str, bold: bool = False, italic: bool = False, color: str = "default") -> dict[str, Any]:
    return {"object": "block", "type": "paragraph", "paragraph": {"rich_text": _rt(text, bold=bold, italic=italic, color=color)}}


def _todo(text: str, checked: bool = False) -> dict[str, Any]:
    return {"object": "block", "type": "to_do", "to_do": {"rich_text": _rt(text), "checked": checked}}


def _bullet(text: str, bold: bool = False) -> dict[str, Any]:
    return {"object": "block", "type": "bulleted_list_item", "bulleted_list_item": {"rich_text": _rt(text, bold=bold)}}


def _divider() -> dict[str, Any]:
    return {"object": "block", "type": "divider", "divider": {}}


def _col(children: list[dict[str, Any]]) -> dict[str, Any]:
    return {"object": "block", "type": "column", "column": {"children": children}}


def _col_list(columns: list[list[dict[str, Any]]]) -> dict[str, Any]:
    return {"object": "block", "type": "column_list", "column_list": {"children": [_col(c) for c in columns]}}


def _select_opts(items: list[tuple[str, str]]) -> dict[str, Any]:
    return {"select": {"options": [{"name": n, "color": c} for n, c in items]}}


def _rel(db_id: str, dual_name: str | None = None) -> dict[str, Any]:
    if dual_name:
        return {"relation": {"database_id": db_id, "type": "dual_property", "dual_property": {"synced_property_name": dual_name}}}
    return {"relation": {"database_id": db_id, "type": "single_property", "single_property": {}}}


def _formula(expr: str) -> dict[str, Any]:
    return {"formula": {"expression": expr}}


def extract_page_id(raw: str) -> str:
    cleaned = raw.strip().split("?")[0].split("#")[0]
    matches = re.findall(r"([0-9a-fA-F]{32})", cleaned.replace("-", ""))
    if not matches:
        raise ValueError(
            "No se encontró un ID de página válido de Notion. "
            "En tu página vacía de Notion haz clic en Compartir → Copiar enlace y pégalo completo."
        )
    hex32 = matches[-1].lower()
    return f"{hex32[:8]}-{hex32[8:12]}-{hex32[12:16]}-{hex32[16:20]}-{hex32[20:]}"


class NotionClient:
    def __init__(self, token: str, dry_run: bool = False) -> None:
        self.token = token.strip()
        self.dry_run = dry_run
        self._dry_counter = 0
        self.dry_payloads: list[tuple[str, str, dict[str, Any]]] = []
        self._ssl_ctx = ssl.create_default_context()

    def request(self, method: str, path: str, payload: dict[str, Any] | None = None) -> dict[str, Any]:
        if self.dry_run:
            # Verify payload is strictly JSON serializable
            if payload is not None:
                json.dumps(payload, ensure_ascii=False)
            self._dry_counter += 1
            fake_id = f"00000000-0000-4000-8000-{self._dry_counter:012d}"
            self.dry_payloads.append((method, path, payload or {}))
            out: dict[str, Any] = {"id": fake_id, "url": f"https://www.notion.so/{fake_id.replace('-', '')}"}
            if method == "PATCH" and path.endswith("/children") and payload and payload.get("children"):
                out["results"] = [
                    {"id": f"00000000-0000-4000-9000-{self._dry_counter:08d}{idx:04d}", "type": b.get("type", "block")}
                    for idx, b in enumerate(payload["children"])
                ]
            return out

        url = f"{NOTION_API}{path}"
        data = json.dumps(payload).encode("utf-8") if payload is not None else None
        req = urllib.request.Request(
            url,
            data=data,
            method=method,
            headers={
                "Authorization": f"Bearer {self.token}",
                "Notion-Version": NOTION_VERSION,
                "Content-Type": "application/json",
            },
        )
        for attempt in range(5):
            try:
                with urllib.request.urlopen(req, timeout=35, context=self._ssl_ctx) as resp:
                    return json.loads(resp.read().decode("utf-8"))
            except urllib.error.HTTPError as e:
                body = e.read().decode("utf-8", errors="replace")
                if e.code == 429 and attempt < 4:
                    retry_after = float(e.headers.get("Retry-After") or (1.5 * (attempt + 1)))
                    time.sleep(min(retry_after, 6.0))
                    continue
                if e.code == 401:
                    raise RuntimeError("Token inválido o revocado. Verifica que comience con 'ntn_' o 'secret_'.") from e
                if e.code in (403, 404):
                    raise RuntimeError(
                        "Tu integración aún no tiene permiso en esa página de Notion. "
                        "Abre tu página en Notion → clic en '•••' (arriba a la derecha) → 'Conexiones' → selecciona tu integración."
                    ) from e
                raise RuntimeError(f"Error de Notion API ({e.code}): {body[:400]}") from e
        raise RuntimeError("Límite de peticiones excedido en Notion API.")

    def create_page(
        self,
        parent: dict[str, Any],
        properties: dict[str, Any],
        children: list[dict[str, Any]] | None = None,
        icon: dict[str, Any] | None = None,
        cover: dict[str, Any] | None = None,
    ) -> dict[str, Any]:
        payload: dict[str, Any] = {"parent": parent, "properties": properties}
        if icon:
            payload["icon"] = icon
        if cover:
            payload["cover"] = cover
        if children:
            payload["children"] = children
        return self.request("POST", "/pages", payload)

    def create_database(
        self,
        parent_page_id: str,
        title: str,
        icon: dict[str, Any],
        properties: dict[str, Any],
        is_inline: bool = True,
    ) -> dict[str, Any]:
        payload: dict[str, Any] = {
            "parent": {"type": "page_id", "page_id": parent_page_id},
            "icon": icon,
            "title": _rt(title),
            "is_inline": is_inline,
            "properties": properties,
        }
        return self.request("POST", "/databases", payload)

    def update_database(self, database_id: str, properties: dict[str, Any]) -> dict[str, Any]:
        return self.request("PATCH", f"/databases/{database_id}", {"properties": properties})

    def append_blocks(self, block_id: str, children: list[dict[str, Any]], after: str | None = None) -> dict[str, Any]:
        body: dict[str, Any] = {"children": children}
        if after:
            body["after"] = after
        return self.request("PATCH", f"/blocks/{block_id}/children", body)


def _nav_mention(page_id: str, hint: str) -> dict[str, Any]:
    return {
        "object": "block",
        "type": "paragraph",
        "paragraph": {
            "rich_text": [
                {"type": "mention", "mention": {"type": "page", "page": {"id": page_id}}},
                {"type": "text", "text": {"content": f" — {hint}"}, "annotations": {"color": "gray"}},
            ]
        },
    }


def install_notion_ultimate(
    client: NotionClient,
    target_page_id: str,
    theme_key: str = "cobalt",
    progress_cb: Callable[[str], None] | None = None,
) -> dict[str, Any]:
    """Construct the complete 5-Hub, 18-Database, 5-Live-Widget, Zero-Emoji Notion OS 2027 ULTIMATE."""
    tk = theme_key.lower() if theme_key.lower() in THEMES else "cobalt"
    th = THEMES[tk]
    c1, c2, cf = th["callout"], th["callout_alt"], th["callout_focus"]

    def log(msg: str) -> None:
        if progress_cb:
            progress_cb(msg)

    w_clock = f"{WIDGETS_BASE}/clock.html?theme={tk}"
    w_year = f"{WIDGETS_BASE}/year-progress.html?theme={tk}"
    w_track = f"{WIDGETS_BASE}/daily-tracker.html?theme={tk}"
    w_pomo = f"{WIDGETS_BASE}/pomodoro.html?theme={tk}"
    w_okr = f"{WIDGETS_BASE}/okr-gauge.html?theme={tk}"

    # =========================================================================
    # 1. CREATE MASTER COMMAND HUB PAGE (COVER + 512px ICON + HERO CALLOUT)
    # =========================================================================
    log(f"[1/8] Creando Command Hub ({th['name']}) con portada 1500x400 e ícono personalizado...")
    hub = client.create_page(
        parent={"type": "page_id", "page_id": target_page_id},
        cover=_ext_cover(tk, "cover_hub.jpg"),
        icon={"type": "external", "external": {"url": f"{CDN_BASE}/{tk}/icon_512.png"}},
        properties={"title": {"title": _rt(f"TheBestPlanner 2027 · Notion OS Ultimate ({th['name']})")}},
        children=[
            _callout(
                tk, "ui_spark",
                f"{th['quote']}  —  {th['name']} · 5 Hubs Despejados · 18 Bases Relacionales · Fórmulas 2.0 · Modo ADHD · 5 Widgets en Vivo.",
                c1, bold=True,
            ),
        ],
    )
    hub_id = hub["id"]
    kpi_resp = client.append_blocks(hub_id, [_img_block(f"{CDN_BASE}/{tk}/kpi_strip.png")])
    kpi_block_id = (kpi_resp.get("results") or [{}])[0].get("id")

    # =========================================================================
    # 2. CREATE ALL 5 SUB-HUB PAGES FIRST SO WE CAN LINK THEM IN COLUMN 1
    # =========================================================================
    log("[2/8] Creando los 5 Sub-Hubs dedicados con portadas e íconos a juego...")

    hub_myday = client.create_page(
        parent={"type": "page_id", "page_id": hub_id},
        cover=_ext_cover(tk, "cover_myday.jpg"),
        icon=_ext_icon(tk, "hub_myday"),
        properties={"title": {"title": _rt("Hub 01 · Mi Día, Enfoque y Modo ADHD")}},
        children=[
            _img_block(f"{CDN_BASE}/{tk}/sec_01_myday.png"),
            _col_list([
                [
                    _callout(tk, "ui_energy", "Ritual de Mañana (3 min)", c1, True, [
                        _todo("Definir tu Nivel de Energía de hoy (Alta / Media / Baja)"),
                        _todo("Marcar máximo 3 tareas como Daily Key 3 en Master Tasks"),
                        _todo("Iniciar 1er bloque Pomodoro sin mensajes ni redes"),
                    ]),
                ],
                [
                    _callout(tk, "ui_brain_dump", "Menú de Dopamina & Cierre Nocturno", cf, True, [
                        _todo("Pausa activa 10 min sin celular cuando baje la energía"),
                        _todo("Registrar gratitud, energía y victoria del día en tu Diario"),
                        _todo("Dejar elegida la Prioridad #1 de mañana"),
                    ]),
                ],
            ]),
        ],
    )

    hub_vision = client.create_page(
        parent={"type": "page_id", "page_id": hub_id},
        cover=_ext_cover(tk, "cover_vision.jpg"),
        icon=_ext_icon(tk, "hub_vision"),
        properties={"title": {"title": _rt("Hub 02 · Visión, Pilares y Metas (12-Week Year)")}},
        children=[
            _img_block(f"{CDN_BASE}/{tk}/sec_02_vision.png"),
            _callout(tk, "hub_vision", "Arquitectura PARA + 12-Week Year: cada proyecto y tarea diaria responde a uno de tus 4 Pilares y a un OKR trimestral medible.", c1, True),
        ],
    )

    hub_brain = client.create_page(
        parent={"type": "page_id", "page_id": hub_id},
        cover=_ext_cover(tk, "cover_brain.jpg"),
        icon=_ext_icon(tk, "hub_brain"),
        properties={"title": {"title": _rt("Hub 03 · Segundo Cerebro y Aprendizaje")}},
        children=[
            _img_block(f"{CDN_BASE}/{tk}/sec_03_brain.png"),
            _callout(tk, "ui_ai", "AI Bridge iPad → Notion: fotografía tu hoja manuscrita de GoodNotes/reMarkable y pega el prompt de AI Bridge para extraer resumen, tareas y eventos de calendario en 15 segundos.", c2, True),
        ],
    )

    hub_wellness = client.create_page(
        parent={"type": "page_id", "page_id": hub_id},
        cover=_ext_cover(tk, "cover_wellness.jpg"),
        icon=_ext_icon(tk, "hub_wellness"),
        properties={"title": {"title": _rt("Hub 04 · Bienestar, Hábitos y Estilo de Vida")}},
        children=[
            _img_block(f"{CDN_BASE}/{tk}/sec_04_wellness.png"),
            _callout(tk, "hub_wellness", "Sistema integral de vida: Hábitos con Momentum XP, Comidas + Lista de Súper, Fitness Log, Viajes 2027, Home Reset por habitación y 12 Rituales Mensuales.", c1, True),
        ],
    )

    hub_business = client.create_page(
        parent={"type": "page_id", "page_id": hub_id},
        cover=_ext_cover(tk, "cover_business.jpg"),
        icon=_ext_icon(tk, "hub_business"),
        properties={"title": {"title": _rt("Hub 05 · Riqueza, Finanzas y Suite Ejecutiva CEO")}},
        children=[
            _img_block(f"{CDN_BASE}/{tk}/sec_05_business.png"),
            _callout(tk, "hub_business", "Control financiero y directivo: Cashflow P&L, Suscripciones anualizadas con alerta de renovación, CRM comercial ponderado y Decision Journal con revisión a 90 días.", c2, True),
        ],
    )

    # =========================================================================
    # 3. INSERT 3-COLUMN MAGAZINE COMMAND DASHBOARD + VISION BOARD ABOVE SUB-HUBS
    # =========================================================================
    log("[3/8] Insertando tablero revista en 3 columnas + 5 widgets en vivo + Vision Board...")
    col1 = [
        _h3("Navegación · 5 Hubs"),
        _callout(
            tk, "hub_command",
            "Acceso Directo a tus 5 Hubs (18 Bases Relacionales):",
            c1, bold=True,
            children=[
                _nav_mention(hub_myday["id"], "Key 3 · ADHD · Diario"),
                _nav_mention(hub_vision["id"], "PARA · Vision · OKRs · Proyectos"),
                _nav_mention(hub_brain["id"], "Notas · AI Bridge · Libros"),
                _nav_mention(hub_wellness["id"], "Hábitos XP · Comidas · Fitness · Viajes · Home"),
                _nav_mention(hub_business["id"], "P&L · Suscripciones · CRM · Decisiones 90D"),
            ],
        ),
        _callout(
            tk, "ui_energy",
            "Modo ADHD · Chequeo de Energía (30s)",
            cf, bold=True,
            children=[
                _bullet("Energía Alta: ataca tu Prioridad #1 en Deep Work (90 min)."),
                _bullet("Energía Media: juntas, seguimiento CRM y revisión de proyectos."),
                _bullet("Energía Baja: Menú de Dopamina — caminata 10 min, agua fría o música sin letras."),
            ],
        ),
        _callout(
            tk, "ui_brain_dump",
            "Reinicio Hoy · Brain Dump Cero Culpa",
            c2, bold=True,
            children=[
                _todo("Vacía aquí cualquier pendiente que te quite paz mental"),
                _todo("Elige SOLO 1 victoria mínima viable para hoy"),
                _todo("Mueve lo demás a mañana sin culpa y respira"),
            ],
        ),
    ]
    col2 = [
        _h3("Enfoque del Día · Reloj & Año 2027"),
        _embed_block(w_clock),
        _embed_block(w_year),
        _callout(
            tk, "db_tasks",
            "Daily Key 3 · Tus 3 Prioridades Innegociables Hoy",
            c1, bold=True,
            children=[
                _todo("Prioridad #1 (Impacto máximo — bloque 90 min sin notificaciones)"),
                _todo("Prioridad #2 (Avance estratégico o entregable clave)"),
                _todo("Prioridad #3 (Cierre operativo o conversación pendiente)"),
            ],
        ),
    ]
    col3 = [
        _h3("Widgets Interactivos & Momentum"),
        _embed_block(w_track),
        _embed_block(w_pomo),
        _embed_block(w_okr),
    ]

    client.append_blocks(
        hub_id,
        [
            _col_list([col1, col2, col3]),
            _divider(),
            _h2("Vision Board 2027 · Galería de Intención"),
            _col_list([
                [_img_block(f"{CDN_BASE}/{tk}/vision_01.jpg", "01 · Libertad & Legado")],
                [_img_block(f"{CDN_BASE}/{tk}/vision_02.jpg", "02 · Vitalidad & Enfoque")],
                [_img_block(f"{CDN_BASE}/{tk}/vision_03.jpg", "03 · Exploración & Presencia")],
            ]),
            _img_block(f"{CDN_BASE}/{tk}/quote_card.png"),
            _divider(),
            _h2("Espacios del Sistema · 5 Hubs Despejados"),
            _p("Cada Hub aloja sus bases conectadas con Fórmulas 2.0 para mantener tu Command Hub rápido y elegante en Mac, iPad e iPhone.", color="gray"),
        ],
        after=kpi_block_id,
    )

    # =========================================================================
    # 4. HUB 02 DATABASES (01 PILARES, 02 VISION BOARD, 03 OKRs, 04 PROYECTOS)
    # =========================================================================
    log("[4/8] Construyendo Hub 02 (Bases 01–04: Pilares, Vision Board, OKRs 2.0 y Proyectos)...")

    # DB 01: Pilares y Áreas PARA
    db_pillars = client.create_database(
        hub_vision["id"], "01 · Pilares y Áreas PARA 2027", _ext_icon(tk, "db_pillars"),
        {
            "Pilar": {"title": {}},
            "Estrella Polar 2027": {"rich_text": {}},
            "Horizonte": _select_opts([("Diario", "orange"), ("Semanal", "blue"), ("2027 Anual", "purple"), ("2027–2029", "green")]),
            "Estado": _select_opts([("Activo", "green"), ("En Revisión", "yellow")]),
        },
    )
    pillar_ids: dict[str, str] = {}
    for pname, star, hor in [
        ("Negocio y Crecimiento", "Escalar ingresos digitales recurrentes con margen operativo > 65%", "2027 Anual"),
        ("Salud y Energía", "Energía física sostenida, sueño reparador y 4 sesiones de entreno/semana", "Diario"),
        ("Relaciones y Familia", "Presencia plena en casa y fines de semana sin fricción operativa", "Semanal"),
        ("Maestría y Legado", "Construir sistemas digitales propios que liberen tiempo mental", "2027–2029"),
    ]:
        r = client.create_page(
            {"database_id": db_pillars["id"]},
            {
                "Pilar": {"title": _rt(pname)},
                "Estrella Polar 2027": {"rich_text": _rt(star)},
                "Horizonte": {"select": {"name": hor}},
                "Estado": {"select": {"name": "Activo"}},
            },
            icon=_ext_icon(tk, "db_pillars"),
        )
        pillar_ids[pname] = r["id"]

    # DB 02: Vision Board 2027 (Galería con portadas HD)
    db_vision = client.create_database(
        hub_vision["id"], "02 · Vision Board 2027 (Galería)", _ext_icon(tk, "db_vision"),
        {
            "Visión / Meta": {"title": {}},
            "Pilar": _rel(db_pillars["id"]),
            "Horizonte": _select_opts([("Q1–Q2 2027", "orange"), ("Q3–Q4 2027", "blue"), ("Estilo de Vida", "pink")]),
            "Afirmación": {"rich_text": {}},
            "Logrado": {"checkbox": {}},
        },
    )
    for v_title, v_pil, v_hor, v_aff, v_img in [
        ("Libertad de Tiempo y Sistemas Propios", "Negocio y Crecimiento", "Q1–Q2 2027", "Construyo activos digitales que operan con claridad y margen alto.", "vision_01.jpg"),
        ("Energía Sostenida y Enfoque Calmo", "Salud y Energía", "Estilo de Vida", "Entreno 4 veces por semana y protejo mi primera hora de enfoque.", "vision_02.jpg"),
        ("Viajes Memorables y Presencia Total", "Relaciones y Familia", "Q3–Q4 2027", "Disfruto cada viaje y cada fin de semana con presencia absoluta.", "vision_03.jpg"),
    ]:
        client.create_page(
            {"database_id": db_vision["id"]},
            {
                "Visión / Meta": {"title": _rt(v_title)},
                "Pilar": {"relation": [{"id": pillar_ids[v_pil]}]},
                "Horizonte": {"select": {"name": v_hor}},
                "Afirmación": {"rich_text": _rt(v_aff)},
                "Logrado": {"checkbox": False},
            },
            cover=_ext_cover(tk, v_img),
            icon=_ext_icon(tk, "db_vision"),
            children=[_img_block(f"{CDN_BASE}/{tk}/{v_img}", v_aff)],
        )

    # DB 03: OKRs Anuales y Sprints 12 Semanas (Formula 2.0 Visual Bar)
    db_okrs = client.create_database(
        hub_vision["id"], "03 · OKRs Anuales y Sprints 12 Semanas", _ext_icon(tk, "db_okrs"),
        {
            "Objetivo / Resultado Clave": {"title": {}},
            "Pilar": _rel(db_pillars["id"]),
            "Sprint 12S": _select_opts([("Q1 (Sem 1–12)", "orange"), ("Q2 (Sem 13–24)", "blue"), ("Q3 (Sem 25–36)", "purple"), ("Q4 (Sem 37–52)", "green")]),
            "Meta": {"number": {"format": "number"}},
            "Actual": {"number": {"format": "number"}},
            "Progreso": _formula(
                'lets(p, if(prop("Meta") > 0, min(1, max(0, prop("Actual") / prop("Meta"))), 0), '
                'f, round(p * 10), '
                'style(repeat("█", f) + repeat("░", 10 - f) + " " + format(round(p * 100)) + "%", '
                'ifs(p >= 0.85, "green", p >= 0.5, "blue", p >= 0.25, "orange", "red"), "b"))'
            ),
            "Estado": _select_opts([("Planificado", "gray"), ("En Curso", "blue"), ("En Riesgo", "red"), ("Completado", "green")]),
        },
    )
    okr_ids: dict[str, str] = {}
    for title, pil, q, meta, act, st in [
        ("Alcanzar 500 ventas de TheBestPlanner 2027", "Negocio y Crecimiento", "Q1 (Sem 1–12)", 500, 120, "En Curso"),
        ("Mantener margen operativo neto superior al 65%", "Negocio y Crecimiento", "Q1 (Sem 1–12)", 65, 68, "En Curso"),
        ("Completar 4 entrenamientos semanales todo el año", "Salud y Energía", "Q1 (Sem 1–12)", 52, 8, "En Curso"),
        ("Proteger 52 fines de semana libres de operación", "Relaciones y Familia", "Q1 (Sem 1–12)", 52, 6, "En Curso"),
        ("Publicar 24 guías de alto valor y sistemas propios", "Maestría y Legado", "Q2 (Sem 13–24)", 24, 4, "Planificado"),
    ]:
        r = client.create_page(
            {"database_id": db_okrs["id"]},
            {
                "Objetivo / Resultado Clave": {"title": _rt(title)},
                "Pilar": {"relation": [{"id": pillar_ids[pil]}]},
                "Sprint 12S": {"select": {"name": q}},
                "Meta": {"number": meta},
                "Actual": {"number": act},
                "Estado": {"select": {"name": st}},
            },
            icon=_ext_icon(tk, "db_okrs"),
        )
        okr_ids[title] = r["id"]

    # DB 04: Proyectos Maestros (Relation → OKRs & Pilares; Rollup added after DB 05)
    db_projects = client.create_database(
        hub_vision["id"], "04 · Proyectos Maestros 2027", _ext_icon(tk, "db_projects"),
        {
            "Proyecto": {"title": {}},
            "OKR Vinculado": _rel(db_okrs["id"]),
            "Pilar": _rel(db_pillars["id"]),
            "Prioridad": _select_opts([("P1 Crítico", "red"), ("P2 Alto", "orange"), ("P3 Normal", "gray")]),
            "Estado": _select_opts([("Planificado", "gray"), ("Activo", "blue"), ("En Pausa", "yellow"), ("Completado", "green")]),
            "Fecha Entrega": {"date": {}},
            "Criterio de Éxito": {"rich_text": {}},
        },
    )
    proj_ids: dict[str, str] = {}
    for pname, okr_k, pil_k, prio, st, due, crit in [
        ("Lanzamiento Global thebestplanner.app + Etsy", "Alcanzar 500 ventas de TheBestPlanner 2027", "Negocio y Crecimiento", "P1 Crítico", "Activo", "2027-01-31", "Dominio + Stripe + 8 listados Etsy activos"),
        ("Ecosistema Notion OS 2027 Ultimate (7 Temas)", "Alcanzar 500 ventas de TheBestPlanner 2027", "Negocio y Crecimiento", "P1 Crítico", "Activo", "2027-01-15", "7 enlaces de duplicación 1-clic publicados"),
        ("Plan de Salud & Energía Q1", "Completar 4 entrenamientos semanales todo el año", "Salud y Energía", "P1 Crítico", "Activo", "2027-03-31", "12 semanas consecutivas cumpliendo rutina"),
        ("Viaje Familiar de Verano 2027", "Proteger 52 fines de semana libres de operación", "Relaciones y Familia", "P2 Alto", "Planificado", "2027-07-15", "Itinerario, vuelos y presupuesto 100% cubiertos"),
    ]:
        r = client.create_page(
            {"database_id": db_projects["id"]},
            {
                "Proyecto": {"title": _rt(pname)},
                "OKR Vinculado": {"relation": [{"id": okr_ids[okr_k]}]},
                "Pilar": {"relation": [{"id": pillar_ids[pil_k]}]},
                "Prioridad": {"select": {"name": prio}},
                "Estado": {"select": {"name": st}},
                "Fecha Entrega": {"date": {"start": due}},
                "Criterio de Éxito": {"rich_text": _rt(crit)},
            },
            icon=_ext_icon(tk, "db_projects"),
        )
        proj_ids[pname] = r["id"]

    # =========================================================================
    # 5. HUB 01 DATABASES (05 MASTER TASKS + ADHD + XP, 06 DIARIO & BRAIN DUMP)
    # =========================================================================
    log("[5/8] Construyendo Hub 01 (Bases 05–06: Master Tasks Daily Key 3 + Energía ADHD + Diario)...")

    # DB 05: Master Tasks y Daily Key 3 (Dual Relation → Proyectos for automatic Rollup!)
    db_tasks = client.create_database(
        hub_myday["id"], "05 · Master Tasks, Daily Key 3 y Modo ADHD", _ext_icon(tk, "db_tasks"),
        {
            "Tarea": {"title": {}},
            "Completada": {"checkbox": {}},
            "Daily Key 3": {"checkbox": {}},
            "Proyecto": _rel(db_projects["id"], dual_name="Tareas Vinculadas"),
            "Nivel Energía": _select_opts([("Alta (Deep Work)", "orange"), ("Media (Gestión)", "blue"), ("Baja (Ligera)", "green")]),
            "Eisenhower": _select_opts([("Q1 · Hacer Ya", "red"), ("Q2 · Programar", "blue"), ("Q3 · Delegar", "yellow"), ("Q4 · Eliminar", "gray")]),
            "Recurrencia": _select_opts([("Única", "gray"), ("Diaria", "green"), ("Semanal", "blue"), ("Mensual", "purple")]),
            "Fecha Límite": {"date": {}},
            "XP": {"number": {"format": "number"}},
            "Semáforo": _formula(
                'ifs(prop("Completada"), style("HECHO +" + format(prop("XP")) + " XP", "green", "b"), '
                'empty(prop("Fecha Límite")), style("SIN FECHA", "gray"), '
                'dateBetween(prop("Fecha Límite"), now(), "days") < 0, style("VENCIDA", "red", "b"), '
                'prop("Daily Key 3"), style("KEY 3 HOY", "orange", "b"), '
                'dateBetween(prop("Fecha Límite"), now(), "days") <= 2, style("PRÓXIMA", "blue", "b"), '
                'style("EN TIEMPO", "gray"))'
            ),
        },
    )
    # Upgrade DB 04 Proyectos with automatic % Rollup from DB 05 Tasks!
    client.update_database(
        db_projects["id"],
        {
            "Avance Tareas": {
                "rollup": {
                    "relation_property_name": "Tareas Vinculadas",
                    "rollup_property_name": "Completada",
                    "function": "percent_checked",
                }
            }
        },
    )

    for task, done, k3, p_key, energy, eisen, rec, due, xp in [
        ("Activar publicación 'Permitir duplicar como plantilla' en mis 7 temas", False, True, "Ecosistema Notion OS 2027 Ultimate (7 Temas)", "Alta (Deep Work)", "Q1 · Hacer Ya", "Única", "2027-01-04", 50),
        ("Registrar dominio thebestplanner.app y activar Stripe Live", False, True, "Lanzamiento Global thebestplanner.app + Etsy", "Alta (Deep Work)", "Q1 · Hacer Ya", "Única", "2027-01-05", 50),
        ("Publicar los 8 anuncios individuales en Etsy con screenshots HD", False, True, "Lanzamiento Global thebestplanner.app + Etsy", "Media (Gestión)", "Q2 · Programar", "Única", "2027-01-06", 40),
        ("Bloque de entrenamiento de fuerza 45 min", True, False, "Plan de Salud & Energía Q1", "Media (Gestión)", "Q2 · Programar", "Semanal", "2027-01-03", 30),
        ("Revisión ejecutiva semanal (15 min) y calibración de OKRs", False, False, "Ecosistema Notion OS 2027 Ultimate (7 Temas)", "Media (Gestión)", "Q2 · Programar", "Semanal", "2027-01-10", 25),
        ("Ordenar escritorio y bandeja de entrada (tarea energía baja)", False, False, "Plan de Salud & Energía Q1", "Baja (Ligera)", "Q2 · Programar", "Semanal", "2027-01-08", 15),
    ]:
        client.create_page(
            {"database_id": db_tasks["id"]},
            {
                "Tarea": {"title": _rt(task)},
                "Completada": {"checkbox": done},
                "Daily Key 3": {"checkbox": k3},
                "Proyecto": {"relation": [{"id": proj_ids[p_key]}]},
                "Nivel Energía": {"select": {"name": energy}},
                "Eisenhower": {"select": {"name": eisen}},
                "Recurrencia": {"select": {"name": rec}},
                "Fecha Límite": {"date": {"start": due}},
                "XP": {"number": xp},
            },
            icon=_ext_icon(tk, "db_tasks"),
        )

    # DB 06: Diario, Gratitud y Reinicio Hoy (Brain Dump)
    db_journal = client.create_database(
        hub_myday["id"], "06 · Diario, Gratitud y Reinicio Hoy", _ext_icon(tk, "db_journal"),
        {
            "Entrada": {"title": {}},
            "Fecha": {"date": {}},
            "Energía (1-5)": {"number": {"format": "number"}},
            "Claridad (1-5)": {"number": {"format": "number"}},
            "Índice Hoy": _formula(
                'lets(avg, (prop("Energía (1-5)") + prop("Claridad (1-5)")) / 2, '
                'style(format(avg) + "/5 · " + ifs(avg >= 4.5, "ÓPTIMO", avg >= 3.5, "SÓLIDO", avg >= 2.5, "MODERADO", "REINICIO SUAVE"), '
                'ifs(avg >= 4.5, "green", avg >= 3.5, "blue", avg >= 2.5, "orange", "red"), "b"))'
            ),
            "3 Gratitudes": {"rich_text": {}},
            "Victoria del Día": {"rich_text": {}},
            "Brain Dump Cero Culpa": {"rich_text": {}},
        },
    )
    for j_title, j_date, en, cl, grat, vic, bd in [
        ("Arranque de Semana · Claridad Total", "2027-01-04", 5, 5, "Salud, familia presente, equipo alineado", "Terminar arquitectura completa del sistema 2027", "Agendar revisión médica anual sin prisa"),
        ("Día de Enfoque Calmo", "2027-01-05", 4, 5, "Mañana silenciosa, buen descanso, avance real", "90 minutos de Deep Work antes de abrir mensajes", "Simplificar carpeta de descargas en Mac"),
    ]:
        client.create_page(
            {"database_id": db_journal["id"]},
            {
                "Entrada": {"title": _rt(j_title)},
                "Fecha": {"date": {"start": j_date}},
                "Energía (1-5)": {"number": en},
                "Claridad (1-5)": {"number": cl},
                "3 Gratitudes": {"rich_text": _rt(grat)},
                "Victoria del Día": {"rich_text": _rt(vic)},
                "Brain Dump Cero Culpa": {"rich_text": _rt(bd)},
            },
            icon=_ext_icon(tk, "db_journal"),
        )

    # =========================================================================
    # 6. HUB 03 DATABASES (07 SEGUNDO CEREBRO & AI BRIDGE, 08 LIBROS & CURSOS)
    # =========================================================================
    log("[6/8] Construyendo Hub 03 (Bases 07–08: Segundo Cerebro PARA + Biblioteca con Barra 2.0)...")

    # DB 07: Segundo Cerebro, Notas y Prompts IA
    db_brain = client.create_database(
        hub_brain["id"], "07 · Segundo Cerebro, Notas y Prompts IA", _ext_icon(tk, "db_brain"),
        {
            "Título": {"title": {}},
            "Tipo": _select_opts([("Prompt IA Bridge", "orange"), ("SOP / Proceso", "blue"), ("Nota de Estudio", "green"), ("Recurso", "purple")]),
            "Pilar": _rel(db_pillars["id"]),
            "Proyecto": _rel(db_projects["id"]),
            "Resumen Accionable": {"rich_text": {}},
            "Estado": _select_opts([("Bandeja", "gray"), ("Activo", "blue"), ("Evergreen", "green")]),
        },
    )
    for b_t, b_type, b_pil, b_proj, b_res, b_st in [
        ("Prompt AI Bridge — Foto de iPad a Tareas en Notion", "Prompt IA Bridge", "Negocio y Crecimiento", "Ecosistema Notion OS 2027 Ultimate (7 Temas)", "Sube la foto de tu hoja manuscrita + pide Resumen, Tabla Master Tasks y Eventos ICS.", "Evergreen"),
        ("Protocolo de Revisión Ejecutiva de Domingo (15 min)", "SOP / Proceso", "Maestría y Legado", "Ecosistema Notion OS 2027 Ultimate (7 Temas)", "1) Vaciar cabeza 2) Celebrar 3 victorias 3) Revisar CRM/OKRs 4) Fijar 3 Rocas.", "Evergreen"),
        ("Playbook de Lanzamiento Etsy + thebestplanner.app", "SOP / Proceso", "Negocio y Crecimiento", "Lanzamiento Global thebestplanner.app + Etsy", "8 anuncios individuales SEO + Stripe Checkout + entrega inmediata sin fricción.", "Activo"),
    ]:
        client.create_page(
            {"database_id": db_brain["id"]},
            {
                "Título": {"title": _rt(b_t)},
                "Tipo": {"select": {"name": b_type}},
                "Pilar": {"relation": [{"id": pillar_ids[b_pil]}]},
                "Proyecto": {"relation": [{"id": proj_ids[b_proj]}]},
                "Resumen Accionable": {"rich_text": _rt(b_res)},
                "Estado": {"select": {"name": b_st}},
            },
            icon=_ext_icon(tk, "db_brain"),
        )

    # DB 08: Biblioteca de Libros y Cursos (Formula 2.0 Reading Bar)
    db_books = client.create_database(
        hub_brain["id"], "08 · Biblioteca de Libros y Cursos", _ext_icon(tk, "db_books"),
        {
            "Título": {"title": {}},
            "Autor / Plataforma": {"rich_text": {}},
            "Formato": _select_opts([("Libro", "blue"), ("Audiolibro", "purple"), ("Curso", "orange"), ("Paper / Artículo", "green")]),
            "Pilar": _rel(db_pillars["id"]),
            "Total": {"number": {"format": "number"}},
            "Avance": {"number": {"format": "number"}},
            "Progreso": _formula(
                'lets(p, if(prop("Total") > 0, min(1, max(0, prop("Avance") / prop("Total"))), 0), '
                'f, round(p * 8), '
                'style(repeat("█", f) + repeat("░", 8 - f) + " " + format(round(p * 100)) + "%", '
                'if(p >= 1, "green", if(p >= 0.4, "blue", "orange")), "b"))'
            ),
            "Calificación": _select_opts([("5/5 Imprescindible", "green"), ("4/5 Muy Bueno", "blue"), ("3/5 Útil", "gray")]),
        },
    )
    for bk, auth, fmt, pil, tot, adv, rat in [
        ("The 12 Week Year", "Brian P. Moran", "Libro", "Maestría y Legado", 208, 160, "5/5 Imprescindible"),
        ("Essentialism", "Greg McKeown", "Libro", "Maestría y Legado", 272, 272, "5/5 Imprescindible"),
        ("Deep Work", "Cal Newport", "Audiolibro", "Negocio y Crecimiento", 304, 210, "5/5 Imprescindible"),
    ]:
        client.create_page(
            {"database_id": db_books["id"]},
            {
                "Título": {"title": _rt(bk)},
                "Autor / Plataforma": {"rich_text": _rt(auth)},
                "Formato": {"select": {"name": fmt}},
                "Pilar": {"relation": [{"id": pillar_ids[pil]}]},
                "Total": {"number": tot},
                "Avance": {"number": adv},
                "Calificación": {"select": {"name": rat}},
            },
            icon=_ext_icon(tk, "db_books"),
        )

    # =========================================================================
    # 7. HUB 04 DATABASES (09 HÁBITOS XP, 10 COMIDAS, 11 FITNESS, 12 VIAJES, 13 HOME, 14 FRASES)
    # =========================================================================
    log("[7/8] Construyendo Hub 04 (Bases 09–14: Hábitos Momentum XP, Comidas, Fitness, Viajes, Home Reset y Frases)...")

    # DB 09: Tracker de Hábitos y Momentum XP
    db_habits = client.create_database(
        hub_wellness["id"], "09 · Tracker de Hábitos y Momentum XP", _ext_icon(tk, "db_habits"),
        {
            "Día": {"title": {}},
            "Fecha": {"date": {}},
            "Deep Work 90m": {"checkbox": {}},
            "Movimiento 30m": {"checkbox": {}},
            "Hidratación 2L": {"checkbox": {}},
            "Lectura 20m": {"checkbox": {}},
            "Cero Pantallas Noche": {"checkbox": {}},
            "Plan Mañana": {"checkbox": {}},
            "Momentum": _formula(
                'lets(s, toNumber(prop("Deep Work 90m")) + toNumber(prop("Movimiento 30m")) + '
                'toNumber(prop("Hidratación 2L")) + toNumber(prop("Lectura 20m")) + '
                'toNumber(prop("Cero Pantallas Noche")) + toNumber(prop("Plan Mañana")), '
                'pct, round(s / 6 * 100), '
                'style(repeat("●", s) + repeat("○", 6 - s) + " " + format(pct) + "%", '
                'ifs(s >= 5, "green", s >= 3, "blue", "orange"), "b"))'
            ),
            "XP Ganados": _formula(
                '(toNumber(prop("Deep Work 90m")) * 25) + (toNumber(prop("Movimiento 30m")) * 20) + '
                '(toNumber(prop("Hidratación 2L")) * 10) + (toNumber(prop("Lectura 20m")) * 15) + '
                '(toNumber(prop("Cero Pantallas Noche")) * 15) + (toNumber(prop("Plan Mañana")) * 15)'
            ),
        },
    )
    for d_lbl, d_iso, h1, h2, h3, h4, h5, h6 in [
        ("Lunes · Semana 01", "2027-01-04", True, True, True, True, True, True),
        ("Martes · Semana 01", "2027-01-05", True, True, True, False, True, True),
        ("Miércoles · Semana 01", "2027-01-06", True, False, True, True, True, True),
    ]:
        client.create_page(
            {"database_id": db_habits["id"]},
            {
                "Día": {"title": _rt(d_lbl)},
                "Fecha": {"date": {"start": d_iso}},
                "Deep Work 90m": {"checkbox": h1},
                "Movimiento 30m": {"checkbox": h2},
                "Hidratación 2L": {"checkbox": h3},
                "Lectura 20m": {"checkbox": h4},
                "Cero Pantallas Noche": {"checkbox": h5},
                "Plan Mañana": {"checkbox": h6},
            },
            icon=_ext_icon(tk, "db_habits"),
        )

    # DB 10: Plan Semanal de Comidas y Lista de Súper
    db_meals = client.create_database(
        hub_wellness["id"], "10 · Plan Semanal de Comidas y Lista de Súper", _ext_icon(tk, "db_meals"),
        {
            "Platillo / Receta": {"title": {}},
            "Día": _select_opts([("Lunes", "blue"), ("Martes", "green"), ("Miércoles", "orange"), ("Jueves", "purple"), ("Viernes", "pink"), ("Sábado", "yellow"), ("Domingo", "gray")]),
            "Momento": _select_opts([("Desayuno", "yellow"), ("Comida", "green"), ("Cena", "blue"), ("Snack", "orange")]),
            "Minutos": {"number": {"format": "number"}},
            "Lista de Súper": {"rich_text": {}},
            "Listo en Alacena": {"checkbox": {}},
        },
    )
    for m_name, m_day, m_mom, m_min, m_ing, m_ok in [
        ("Bowl de Yogurt Griego, Moras y Nueces", "Lunes", "Desayuno", 5, "Yogurt griego, moras, nueces, chía", True),
        ("Salmón a la Plancha con Quinoa y Espárragos", "Lunes", "Comida", 25, "Salmón, quinoa, espárragos, limón", False),
        ("Tacos de Pollo al Limón con Aguacate", "Martes", "Comida", 20, "Pechuga de pollo, aguacate, tortillas maíz", False),
        ("Ensalada Mediterránea con Garbanzo Crujiente", "Miércoles", "Cena", 15, "Espinaca, garbanzo, pepino, queso feta", True),
    ]:
        client.create_page(
            {"database_id": db_meals["id"]},
            {
                "Platillo / Receta": {"title": _rt(m_name)},
                "Día": {"select": {"name": m_day}},
                "Momento": {"select": {"name": m_mom}},
                "Minutos": {"number": m_min},
                "Lista de Súper": {"rich_text": _rt(m_ing)},
                "Listo en Alacena": {"checkbox": m_ok},
            },
            icon=_ext_icon(tk, "db_meals"),
        )

    # DB 11: Entrenamiento y Fitness Log
    db_fitness = client.create_database(
        hub_wellness["id"], "11 · Entrenamiento y Fitness Log", _ext_icon(tk, "db_fitness"),
        {
            "Sesión": {"title": {}},
            "Fecha": {"date": {}},
            "Disciplina": _select_opts([("Fuerza", "orange"), ("Cardio Zona 2", "blue"), ("Movilidad / Yoga", "green"), ("Deporte", "purple")]),
            "Duración (min)": {"number": {"format": "number"}},
            "Intensidad": _select_opts([("Alta", "red"), ("Media", "orange"), ("Recuperación", "green")]),
            "Notas / PR": {"rich_text": {}},
        },
    )
    for f_ses, f_dt, f_dis, f_dur, f_int, f_not in [
        ("Fuerza Tren Superior + Core", "2027-01-04", "Fuerza", 45, "Alta", "Excelente energía, +2.5 kg en press"),
        ("Caminata Rápida Zona 2", "2027-01-05", "Cardio Zona 2", 40, "Media", "Ritmo constante 128 ppm, mente despejada"),
        ("Movilidad y Estiramiento Profundo", "2027-01-07", "Movilidad / Yoga", 25, "Recuperación", "Cero tensión en espalda baja"),
    ]:
        client.create_page(
            {"database_id": db_fitness["id"]},
            {
                "Sesión": {"title": _rt(f_ses)},
                "Fecha": {"date": {"start": f_dt}},
                "Disciplina": {"select": {"name": f_dis}},
                "Duración (min)": {"number": f_dur},
                "Intensidad": {"select": {"name": f_int}},
                "Notas / PR": {"rich_text": _rt(f_not)},
            },
            icon=_ext_icon(tk, "db_fitness"),
        )

    # DB 12: Planeador de Viajes 2027
    db_travel = client.create_database(
        hub_wellness["id"], "12 · Planeador de Viajes 2027", _ext_icon(tk, "db_travel"),
        {
            "Destino / Viaje": {"title": {}},
            "Tipo": _select_opts([("Familia", "pink"), ("Descanso", "green"), ("Negocio", "blue")]),
            "Fecha Salida": {"date": {}},
            "Presupuesto USD": {"number": {"format": "dollar"}},
            "Gastado USD": {"number": {"format": "dollar"}},
            "Balance": _formula(
                'lets(rem, prop("Presupuesto USD") - prop("Gastado USD"), '
                'style((if(rem >= 0, "Disponible $", "Excedido -$")) + format(abs(round(rem))), '
                'if(rem >= 0, "green", "red"), "b"))'
            ),
            "Estado": _select_opts([("Idea", "gray"), ("Reservado", "blue"), ("Listo", "green")]),
        },
    )
    for tr_d, tr_t, tr_dt, tr_b, tr_s, tr_st in [
        ("Escapada Playa & Descanso Q2", "Familia", "2027-04-16", 2400, 650, "Reservado"),
        ("Retiro Estratégico & Naturaleza Q3", "Descanso", "2027-08-12", 1800, 0, "Idea"),
    ]:
        client.create_page(
            {"database_id": db_travel["id"]},
            {
                "Destino / Viaje": {"title": _rt(tr_d)},
                "Tipo": {"select": {"name": tr_t}},
                "Fecha Salida": {"date": {"start": tr_dt}},
                "Presupuesto USD": {"number": tr_b},
                "Gastado USD": {"number": tr_s},
                "Estado": {"select": {"name": tr_st}},
            },
            icon=_ext_icon(tk, "db_travel"),
        )

    # DB 13: Home Reset (Orden por Habitación — ADHD friendly!)
    db_home = client.create_database(
        hub_wellness["id"], "13 · Home Reset (Orden por Habitación)", _ext_icon(tk, "db_home"),
        {
            "Acción de Orden": {"title": {}},
            "Espacio": _select_opts([("Oficina / Estudio", "blue"), ("Cocina", "green"), ("Recámara", "pink"), ("Sala", "orange"), ("Espacio Digital", "purple")]),
            "Frecuencia": _select_opts([("Diario (5 min)", "green"), ("Semanal (15 min)", "blue"), ("Mensual", "purple")]),
            "Minutos": {"number": {"format": "number"}},
            "Completado": {"checkbox": {}},
        },
    )
    for h_act, h_sp, h_fr, h_m, h_ok in [
        ("Despejar escritorio y cables al terminar el día", "Oficina / Estudio", "Diario (5 min)", 5, True),
        ("Reset de cocina y barra limpia antes de dormir", "Cocina", "Diario (5 min)", 5, True),
        ("Vaciar carpeta Descargas y ordenar archivos en Drive", "Espacio Digital", "Semanal (15 min)", 15, False),
        ("Renovar ropa de cama y ventilar recámara", "Recámara", "Semanal (15 min)", 15, False),
    ]:
        client.create_page(
            {"database_id": db_home["id"]},
            {
                "Acción de Orden": {"title": _rt(h_act)},
                "Espacio": {"select": {"name": h_sp}},
                "Frecuencia": {"select": {"name": h_fr}},
                "Minutos": {"number": h_m},
                "Completado": {"checkbox": h_ok},
            },
            icon=_ext_icon(tk, "db_home"),
        )

    # DB 14: Frases Motivacionales y Rituales Mensuales 2027
    db_quotes = client.create_database(
        hub_wellness["id"], "14 · Frases Motivacionales y Rituales 2027", _ext_icon(tk, "db_quotes"),
        {
            "Mes": {"title": {}},
            "Temática": {"rich_text": {}},
            "Frase del Mes": {"rich_text": {}},
            "Autor": {"rich_text": {}},
            "Ritual Clave": {"rich_text": {}},
            "Estado": _select_opts([("Activo", "orange"), ("Planificado", "gray"), ("Completado", "green")]),
        },
    )
    for idx, (m_mes, m_tem, m_q, m_aut, m_rit) in enumerate(MONTHLY_RITUALS_2027):
        client.create_page(
            {"database_id": db_quotes["id"]},
            {
                "Mes": {"title": _rt(f"{idx + 1:02d} · {m_mes}")},
                "Temática": {"rich_text": _rt(m_tem)},
                "Frase del Mes": {"rich_text": _rt(m_q)},
                "Autor": {"rich_text": _rt(m_aut)},
                "Ritual Clave": {"rich_text": _rt(m_rit)},
                "Estado": {"select": {"name": "Activo" if idx == 0 else "Planificado"}},
            },
            icon=_ext_icon(tk, "db_quotes"),
        )

    # =========================================================================
    # 8. HUB 05 DATABASES (15 FINANZAS P&L, 16 SUSCRIPCIONES, 17 CRM, 18 DECISIONES)
    # =========================================================================
    log("[8/8] Construyendo Hub 05 (Bases 15–18: Finanzas P&L, Suscripciones, CRM Ponderado y Decision Journal 90D)...")

    # DB 15: Finanzas Personales y Negocio (Cashflow P&L)
    db_fin = client.create_database(
        hub_business["id"], "15 · Finanzas Personales y Negocio (Cashflow P&L)", _ext_icon(tk, "db_finances"),
        {
            "Concepto": {"title": {}},
            "Mes": _select_opts([("2027-01", "orange"), ("2027-02", "blue"), ("2027-03", "purple"), ("2027-Q2", "green")]),
            "Tipo": _select_opts([("Ingreso", "green"), ("Gasto Fijo", "orange"), ("Inversión / Marketing", "blue")]),
            "Ingresos USD": {"number": {"format": "dollar"}},
            "Gastos USD": {"number": {"format": "dollar"}},
            "Flujo Neto": _formula(
                'lets(n, prop("Ingresos USD") - prop("Gastos USD"), '
                'style((if(n >= 0, "+$", "-$")) + format(abs(round(n))), if(n >= 0, "green", "red"), "b"))'
            ),
            "Estado": _select_opts([("Proyectado", "gray"), ("Pagado / Cobrado", "green")]),
        },
    )
    for fn_c, fn_m, fn_t, fn_i, fn_g, fn_st in [
        ("Ventas TheBestPlanner 2027 (Web Stripe + Etsy)", "2027-01", "Ingreso", 12500, 0, "Proyectado"),
        ("Dominio thebestplanner.app + Infraestructura Cloud", "2027-01", "Gasto Fijo", 0, 120, "Pagado / Cobrado"),
        ("Campañas de Lanzamiento (Meta / TikTok / Etsy Ads)", "2027-01", "Inversión / Marketing", 0, 1400, "Proyectado"),
        ("Licencias Corporativas Teams (10 usuarios)", "2027-02", "Ingreso", 4950, 0, "Proyectado"),
    ]:
        client.create_page(
            {"database_id": db_fin["id"]},
            {
                "Concepto": {"title": _rt(fn_c)},
                "Mes": {"select": {"name": fn_m}},
                "Tipo": {"select": {"name": fn_t}},
                "Ingresos USD": {"number": fn_i},
                "Gastos USD": {"number": fn_g},
                "Estado": {"select": {"name": fn_st}},
            },
            icon=_ext_icon(tk, "db_finances"),
        )

    # DB 16: Control de Suscripciones y Pagos Recurrentes (Annualized Cost Formula 2.0)
    db_subs = client.create_database(
        hub_business["id"], "16 · Control de Suscripciones y Pagos Recurrentes", _ext_icon(tk, "db_subs"),
        {
            "Servicio": {"title": {}},
            "Categoría": _select_opts([("Productividad", "blue"), ("Cloud / Dominio", "purple"), ("Marketing / IA", "orange"), ("Personal", "green")]),
            "Ciclo": _select_opts([("Mensual", "orange"), ("Trimestral", "blue"), ("Anual", "green")]),
            "Costo USD": {"number": {"format": "dollar"}},
            "Costo Anualizado": _formula(
                'lets(a, ifs(prop("Ciclo") == "Mensual", prop("Costo USD") * 12, '
                'prop("Ciclo") == "Trimestral", prop("Costo USD") * 4, prop("Costo USD")), '
                'style("$" + format(round(a)) + "/año", if(a >= 300, "orange", "blue"), "b"))'
            ),
            "Próxima Renovación": {"date": {}},
            "Activa": {"checkbox": {}},
        },
    )
    for sb_s, sb_c, sb_cy, sb_v, sb_dt, sb_a in [
        ("Dominio thebestplanner.app", "Cloud / Dominio", "Anual", 30, "2027-12-04", True),
        ("Google Cloud Run + Firebase Hosting", "Cloud / Dominio", "Mensual", 12, "2027-01-15", True),
        ("Suite IA / Creatividad", "Marketing / IA", "Mensual", 20, "2027-01-20", True),
        ("Notion Personal (Plan Gratuito)", "Productividad", "Anual", 0, "2027-12-31", True),
    ]:
        client.create_page(
            {"database_id": db_subs["id"]},
            {
                "Servicio": {"title": _rt(sb_s)},
                "Categoría": {"select": {"name": sb_c}},
                "Ciclo": {"select": {"name": sb_cy}},
                "Costo USD": {"number": sb_v},
                "Próxima Renovación": {"date": {"start": sb_dt}},
                "Activa": {"checkbox": sb_a},
            },
            icon=_ext_icon(tk, "db_subs"),
        )

    # DB 17: CRM Personal y Pipeline Comercial (Weighted Pipeline Formula 2.0)
    db_crm = client.create_database(
        hub_business["id"], "17 · CRM Personal y Pipeline Comercial", _ext_icon(tk, "db_crm"),
        {
            "Cliente / Contacto": {"title": {}},
            "Etapa": _select_opts([("Lead", "gray"), ("Diagnóstico", "blue"), ("Propuesta", "orange"), ("Negociación", "purple"), ("Ganado", "green")]),
            "Valor USD": {"number": {"format": "dollar"}},
            "Probabilidad %": {"number": {"format": "percent"}},
            "Valor Ponderado": _formula(
                'style("$" + format(round(prop("Valor USD") * prop("Probabilidad %"))), '
                'if(prop("Probabilidad %") >= 0.6, "green", "blue"), "b")'
            ),
            "Próxima Acción": {"rich_text": {}},
            "Seguimiento": {"date": {}},
        },
    )
    for cm_n, cm_e, cm_v, cm_p, cm_a, cm_d in [
        ("Grupo Directivo Alpha (Licencia 10 Equipos)", "Propuesta", 990, 0.65, "Demo en vivo iPad + Notion OS Ultimate", "2027-01-08"),
        ("Consultora Internacional Beta (Alianza)", "Diagnóstico", 3200, 0.45, "Enviar paquete personalizado de 30 licencias", "2027-01-12"),
        ("Creador Productividad Europa (Afiliado DE/FR)", "Negociación", 2400, 0.75, "Activar enlace afiliado 30% comisión", "2027-01-10"),
    ]:
        client.create_page(
            {"database_id": db_crm["id"]},
            {
                "Cliente / Contacto": {"title": _rt(cm_n)},
                "Etapa": {"select": {"name": cm_e}},
                "Valor USD": {"number": cm_v},
                "Probabilidad %": {"number": cm_p},
                "Próxima Acción": {"rich_text": _rt(cm_a)},
                "Seguimiento": {"date": {"start": cm_d}},
            },
            icon=_ext_icon(tk, "db_crm"),
        )

    # DB 18: Juntas y Decision Journal 90 Días (90-Day Review Formula 2.0)
    db_dec = client.create_database(
        hub_business["id"], "18 · Juntas y Decision Journal 90 Días", _ext_icon(tk, "db_decisions"),
        {
            "Decisión / Junta": {"title": {}},
            "Tipo": _select_opts([("Decisión Estratégica", "orange"), ("Junta Directiva", "blue"), ("Revisión 1:1", "green")]),
            "Fecha": {"date": {}},
            "Proyecto": _rel(db_projects["id"]),
            "Resultado Esperado": {"rich_text": {}},
            "Revisado 90D": {"checkbox": {}},
            "Estado 90D": _formula(
                'ifs(prop("Revisado 90D"), style("CALIBRADA", "green", "b"), '
                'empty(prop("Fecha")), style("SIN FECHA", "gray"), '
                'dateBetween(now(), prop("Fecha"), "days") >= 90, style("REVISAR HOY (90D+)", "red", "b"), '
                'style("EN SEGUIMIENTO (" + format(max(0, 90 - dateBetween(now(), prop("Fecha"), "days"))) + "d)", "blue"))'
            ),
        },
    )
    for dc_t, dc_tp, dc_dt, dc_pr, dc_ex, dc_ok in [
        ("Arquitectura 5 Hubs + 18 Bases en 7 Temas sin Emojis", "Decisión Estratégica", "2027-01-04", "Ecosistema Notion OS 2027 Ultimate (7 Temas)", "Posicionar TheBestPlanner como #1 mundial frente a Ultimate Brain y Life OS", False),
        ("Lanzar canal directo thebestplanner.app con Stripe + 8 listados Etsy", "Decisión Estratégica", "2027-01-05", "Lanzamiento Global thebestplanner.app + Etsy", "Capturar 100% de margen en canal directo y tráfico orgánico en Etsy", False),
        ("Junta Semanal de Arranque Q1 2027", "Junta Directiva", "2027-01-06", "Lanzamiento Global thebestplanner.app + Etsy", "Alinear métricas de conversión, soporte y calendario de contenidos", False),
    ]:
        client.create_page(
            {"database_id": db_dec["id"]},
            {
                "Decisión / Junta": {"title": _rt(dc_t)},
                "Tipo": {"select": {"name": dc_tp}},
                "Fecha": {"date": {"start": dc_dt}},
                "Proyecto": {"relation": [{"id": proj_ids[dc_pr]}]},
                "Resultado Esperado": {"rich_text": _rt(dc_ex)},
                "Revisado 90D": {"checkbox": dc_ok},
            },
            icon=_ext_icon(tk, "db_decisions"),
        )

    return {
        "ok": True,
        "theme": tk,
        "theme_name": th["name"],
        "hub_id": hub_id,
        "hub_url": hub.get("url", ""),
        "sub_hubs": 5,
        "databases": 18,
        "widgets": 5,
        "dry_run": client.dry_run,
        "api_calls": len(client.dry_payloads) if client.dry_run else None,
    }


def main() -> None:
    parser = argparse.ArgumentParser(
        description="TheBestPlanner Notion OS 2027 ULTIMATE — Instalador Oficial Multi-Columna (5 Hubs · 18 Bases · 7 Temas)."
    )
    parser.add_argument("--theme", default="", choices=["", *THEMES.keys(), "all"], help="Tema visual o 'all' para los 7 temas")
    parser.add_argument("--token", default="", help="Notion Integration Token (ntn_... o secret_...)")
    parser.add_argument("--page-url", default="", help="URL o ID de tu página vacía en Notion")
    parser.add_argument("--dry-run", action="store_true", help="Valida todos los esquemas JSON y Fórmulas 2.0 sin llamar a Notion")
    args = parser.parse_args()

    if args.dry_run:
        t_arg = args.theme or "cobalt"
        keys = list(THEMES.keys()) if t_arg == "all" else [t_arg]
        total_dbs = 0
        for tk in keys:
            client = NotionClient(token="dry_run", dry_run=True)
            res = install_notion_ultimate(client, "00000000-0000-4000-8000-000000000000", tk)
            dump = json.dumps(client.dry_payloads, ensure_ascii=False)
            emoji_hits = re.findall(r"[\U0001F300-\U0001FAFF\u2600-\u27BF]", dump)
            if emoji_hits:
                raise RuntimeError(f"Emoji detected in {tk} payload: {emoji_hits[:10]}")
            db_posts = sum(1 for m, p, _ in client.dry_payloads if m == "POST" and p == "/databases")
            assert db_posts == 18, f"Expected 18 databases, got {db_posts}"
            total_dbs += db_posts
            print(f"  [DRY-RUN PASS] {THEMES[tk]['num']}_{tk:10s} | {db_posts} DBs | 5 Hubs | 5 Widgets | {res['api_calls']} API calls | 0 emojis")
        print(f"\n[ALL {len(keys)} THEMES VALIDATED · {total_dbs} RELATIONAL DATABASES · 0 EMOJIS · 0 ERRORS]")
        return

    token = args.token.strip()
    page_raw = args.page_url.strip()
    theme_key = args.theme.strip() or "all"

    print("=" * 72)
    print("  THEBESTPLANNER 2027 · CREADOR AUTOMÁTICO DE LOS 7 TEMAS EN NOTION")
    print("=" * 72)

    if not token:
        token = input("\nPega tu Token de Notion (pestaña Configuración -> Mostrar -> Copiar): ").strip()

    client = NotionClient(token=token, dry_run=False)

    # 1. Verify token identity via /users/me
    try:
        me = client.request("GET", "/users/me")
        bot_name = me.get("name") or "(sin nombre)"
        ws_name = ((me.get("bot") or {}).get("workspace_name")) or "(espacio personal)"
        print(f"\n  [OK] Conectado a la integración: '{bot_name}' | Espacio: '{ws_name}'")
    except RuntimeError as exc:
        print(f"\n  [ERROR DE TOKEN] {exc}")
        sys.exit(1)

    # 2. Auto-discover accessible pages via POST /search (eliminates copy-paste URL issues!)
    page_id = ""
    if page_raw:
        page_id = extract_page_id(page_raw)
    else:
        print("  Buscando tus páginas conectadas (ej. 'Maestros 2027')...")
        search_res = client.request("POST", "/search", {"filter": {"value": "page", "property": "object"}, "page_size": 25})
        pages = search_res.get("results") or []

        def _page_title(p: dict[str, Any]) -> str:
            props = p.get("properties") or {}
            for prop in props.values():
                if prop.get("type") == "title":
                    return "".join(t.get("plain_text", "") for t in (prop.get("title") or [])).strip() or "(Sin título)"
            return "(Sin título)"

        if not pages:
            print("\n" + "!" * 72)
            print(f"  La integración '{bot_name}' (Espacio: '{ws_name}') tiene 0 páginas conectadas.")
            print("  Verifica estas 2 cosas en https://app.notion.com/developers :")
            print(f"  1) Que estés editando exactamente la integración '{bot_name}' (mismo Token).")
            print("  2) Pestaña 'Acceso al contenido' -> 'Editar acceso' -> marca 'Maestros 2027' -> Guardar.")
            print("  3) Pestaña 'Configuración' -> asegúrate que Leer/Actualizar/Insertar contenido estén activos -> Guardar.")
            print("!" * 72)
            sys.exit(1)

        # Prefer exact match "Maestros 2027" automatically!
        maestros = [p for p in pages if "maestros" in _page_title(p).lower()]
        if maestros:
            chosen = maestros[0]
            page_id = chosen["id"]
            print(f"  [OK] Página encontrada automáticamente: '{_page_title(chosen)}' ({page_id})")
        elif len(pages) == 1:
            chosen = pages[0]
            page_id = chosen["id"]
            print(f"  [OK] Usando tu página conectada: '{_page_title(chosen)}' ({page_id})")
        else:
            print("\n  Páginas conectadas encontradas:")
            for i, p in enumerate(pages, 1):
                print(f"    {i}. {_page_title(p)}")
            pick = input("\n  Elige el número de página [1]: ").strip() or "1"
            chosen = pages[max(0, min(len(pages) - 1, int(pick) - 1))]
            page_id = chosen["id"]

    # Confirm write access to page_id
    try:
        client.request("GET", f"/pages/{page_id}")
    except RuntimeError as exc:
        print(f"\n  [ERROR ACCESO A PÁGINA {page_id}] {exc}")
        sys.exit(1)

    keys = list(THEMES.keys()) if theme_key == "all" else [theme_key]
    created: list[tuple[str, str, str]] = []

    for idx, tk in enumerate(keys, 1):
        print(f"\n[{idx}/{len(keys)}] Construyendo {THEMES[tk]['name']} ({tk})...")
        res = install_notion_ultimate(client, page_id, tk, progress_cb=lambda m: print(f"  {m}"))
        created.append((tk, THEMES[tk]["name"], res["hub_url"]))

    print("\n" + "=" * 72)
    print(f"  LISTO. SE CREARON {len(created)} WORKSPACE(S) ULTIMATE EN TU NOTION.")
    print("  En cada enlace abajo haz clic en: Compartir -> Publicar -> Permitir duplicar")
    print("-" * 72)
    for tk, name, url in created:
        print(f"  {tk:10s} | {name:24s} | {url}")
    print("=" * 72)


if __name__ == "__main__":
    main()
