#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""One-off: agrega filtro `TIPO DE TIENDA != NO DIGITAL` (field 7279) al nodo
Baserow de lookup del Verificador (tabla 750) en los 3 workflows que lo leen.

Operador confirmado empíricamente contra Baserow REST: `not_equal` (2026-05-30).
Idempotente (no duplica el filtro). Backup por workflow. Dry-run por defecto.

    python n8n/add_tipo_de_tienda_filter.py            # dry-run
    python n8n/add_tipo_de_tienda_filter.py --apply     # aplica + activa + verifica
"""
import argparse
import copy
import os
import sys

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if ROOT not in sys.path:
    sys.path.insert(0, ROOT)

from scripts.n8n_workflow_lib import load_credentials, N8NClient, PutFailedError  # noqa: E402

FILTER_FIELD = 7279
FILTER = {"field": FILTER_FIELD, "operator": "not_equal", "value": "NO DIGITAL"}

# (workflow_id, nodo_objetivo, rol)
TARGETS = [
    ("4UMRwxJdHFfOGHBp", "Obtener Info de cuenta objetivo - SUCURSAL", "[1604] CRITICO (SUCURSAL contains)"),
    ("ddUEORBEtZLzsQF2", "Buscar Sucursal en Verificador de Sucursales", "[2004] defensa (SC BUCEFALO)"),
    ("EuPdIkCORyh0skoB", "Buscar Cuenta Sucursal Bucefalo", "[SUCURSAL] defensa (SC BUCEFALO)"),
]


def get_fields_list(node):
    """Devuelve (fields_list, ok). fields_list es la lista mutable additionalOptions.filters.fields."""
    params = node.get("parameters") or {}
    ao = params.get("additionalOptions") or {}
    filt = ao.get("filters") or {}
    fields = filt.get("fields")
    return fields if isinstance(fields, list) else None


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--apply", action="store_true")
    args = ap.parse_args()
    dry = not args.apply
    client = N8NClient(*load_credentials())

    for wid, node_name, rol in TARGETS:
        print("\n" + "=" * 70)
        print(f"{wid}  {rol}\n  nodo: {node_name!r}")
        wf = client.get_workflow(wid)
        node = client.find_node(wf, node_name)
        if node is None:
            print(f"  ABORTA: nodo no encontrado. Nodos Baserow disponibles:")
            for n in wf.get("nodes", []):
                if n.get("type") == "n8n-nodes-base.baserow":
                    print(f"     - {n['name']!r}")
            sys.exit(1)
        fields = get_fields_list(node)
        if fields is None:
            print("  ABORTA: el nodo no tiene additionalOptions.filters.fields (estructura inesperada)")
            sys.exit(1)
        existing = [f for f in fields if f.get("field") == FILTER_FIELD]
        print(f"  filtros actuales: {fields}")
        if existing:
            print(f"  YA tiene filtro field {FILTER_FIELD} -> idempotente, skip.  active={wf.get('active')}")
            continue

        if not dry:
            _, bpath = client.backup_workflow(wid, label="add_tipo_filter")
            print(f"  backup -> {bpath}")
        wf2 = copy.deepcopy(wf)
        node2 = client.find_node(wf2, node_name)
        get_fields_list(node2).append(dict(FILTER))

        res = client.put_workflow(wid, wf2, dry_run=dry)
        if dry:
            print(f"  DRY-RUN payload -> {res['path']}  (nodos={res['node_count']})")
            print(f"  filtros que QUEDARIAN: {get_fields_list(node2)}")
            continue

        # apply ya hecho por put_workflow(dry_run=False)
        print(f"  PUT aplicado.")
        was_active = bool(wf.get("active"))
        if was_active:
            client.activate(wid)
        # verify
        wf_live = client.get_workflow(wid)
        node_live = client.find_node(wf_live, node_name)
        live_fields = get_fields_list(node_live) or []
        has = any(f.get("field") == FILTER_FIELD and f.get("operator") == "not_equal" for f in live_fields)
        print(f"  VERIFY: filtro 7279 presente={has}  active={wf_live.get('active')}  filtros={live_fields}")
        if not has:
            print("  !! FALLO verificación — revisar / revertir")
            sys.exit(1)
        if was_active and not wf_live.get("active"):
            print("  !! quedó INACTIVO — reintentar activate")
            sys.exit(1)

    print("\n" + ("DRY-RUN OK (sin cambios)" if dry else "APLICADO + VERIFICADO en los 3 workflows"))


if __name__ == "__main__":
    main()
