# -*- coding: utf-8 -*-
"""Fallback post-UPDATE para el workflow Marca->Sucursal V2 (4UMRwxJdHFfOGHBp).

Cierra el gap del path UPDATE-via-cascada: cuando el contacto Marca llega sin
CF id_contacto_sucursal poblado, va por cascada (mail/telefono/nombre), encuentra
contacto sucursal existente, lo actualiza... y el CF Marca queda vacio para
siempre (la siguiente ejecucion volvera por cascada).

Inserta tras 'Actualizar Contacto Cuenta Objetivo - SUCURSAL':

    IF '¿cfValue de Marca estaba vacio?'  (eval: cfValue extraido al inicio)
       true  -> PUT 1 (CF en MARCA = id sucursal encontrado)
                  -> PUT 2 (CF en SUCURSAL = autoref)
       false -> (fin, ya estaba enlazado)

Defensivo: onError=continueRegularOutput en ambos PUTs.

Modo dry-run por defecto; --apply para PUT real + reactivar.
"""
import argparse
import sys
import os
import uuid

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from scripts.n8n_workflow_lib import load_credentials, N8NClient

WID = "4UMRwxJdHFfOGHBp"
BRAND_CF_ID = "E6lI9ykWhqpj7Pmi7Qd3"  # CF id_contacto_sucursal en Marca (hardcoded)

NAME_IF = "cfValue Marca estaba vacio"
NAME_PUT_MARCA = "Autoenlace post-UPDATE: CF en MARCA"
NAME_PUT_SUC = "Autoenlace post-UPDATE: CF en SUCURSAL (autoref)"

# Nodo terminal donde nos enganchamos
SRC_TERMINAL = "Actualizar Contacto Cuenta Objetivo - SUCURSAL"


def build_if_node():
    return {
        "parameters": {
            "conditions": {
                "options": {
                    "caseSensitive": True,
                    "leftValue": "",
                    "typeValidation": "loose",
                    "version": 3,
                },
                "conditions": [
                    {
                        "id": str(uuid.uuid4()),
                        "leftValue": "={{ $('Extraer id_contacto_sucursal de Marca').item.json.cfValue }}",
                        "rightValue": "",
                        "operator": {
                            "type": "string",
                            "operation": "empty",
                            "singleValue": True,
                        },
                    }
                ],
                "combinator": "and",
            },
            "options": {},
        },
        "type": "n8n-nodes-base.if",
        "typeVersion": 2.2,
        "position": [3984, 480],
        "id": str(uuid.uuid4()),
        "name": NAME_IF,
        "notes": (
            "Fallback post-UPDATE: si el cfValue extraido al inicio estaba vacio, "
            "entonces la cascada nos trajo aqui. Autoenlazamos ambos lados para "
            "que la proxima ejecucion vaya por la ruta deterministica."
        ),
    }


def build_put_marca():
    json_body = (
        '={\n'
        '  "customFields": [\n'
        '    {\n'
        f'      "id": "{BRAND_CF_ID}",\n'
        '      "key": "contact.id_contacto_sucursal",\n'
        '      "field_value": "{{ $(\'Obtener datos completos de Contacto objetivo - SUCURSAL\').item.json.id }}"\n'
        '    }\n'
        '  ]\n'
        '}'
    )
    return {
        "parameters": {
            "method": "PUT",
            "url": (
                "=https://services.leadconnectorhq.com/contacts/"
                "{{ $('Webhook').item.json.body.contact_id }}"
            ),
            "sendHeaders": True,
            "headerParameters": {
                "parameters": [
                    {"name": "Accept", "value": "application/json"},
                    {"name": "Version", "value": "2021-07-28"},
                    {
                        "name": "Authorization",
                        "value": (
                            "=Bearer "
                            "{{ $('Datos API Cuenta Origen').item.json['Token/API'] }}"
                        ),
                    },
                    {"name": "Content-Type", "value": "application/json"},
                ]
            },
            "sendBody": True,
            "specifyBody": "json",
            "jsonBody": json_body,
            "options": {"redirect": {"redirect": {}}},
        },
        "type": "n8n-nodes-base.httpRequest",
        "typeVersion": 4.2,
        "position": [4176, 384],
        "id": str(uuid.uuid4()),
        "name": NAME_PUT_MARCA,
        "onError": "continueRegularOutput",
        "notes": "Setea CF id_contacto_sucursal en MARCA = id del contacto sucursal encontrado.",
    }


def build_put_sucursal():
    json_body = (
        '={{ JSON.stringify({ customFields: [ { '
        "id: $('Conseguir Custom Cuenta objetivo - SUCURSAL').first().json.customFields"
        ".find(f => f.fieldKey === 'contact.id_contacto_sucursal')?.id, "
        "key: 'contact.id_contacto_sucursal', "
        "field_value: $('Obtener datos completos de Contacto objetivo - SUCURSAL').item.json.id"
        ' } ] }) }}'
    )
    return {
        "parameters": {
            "method": "PUT",
            "url": (
                "=https://services.leadconnectorhq.com/contacts/"
                "{{ $('Obtener datos completos de Contacto objetivo - SUCURSAL').item.json.id }}"
            ),
            "sendHeaders": True,
            "headerParameters": {
                "parameters": [
                    {"name": "Accept", "value": "application/json"},
                    {"name": "Version", "value": "2021-07-28"},
                    {
                        "name": "Authorization",
                        "value": (
                            "=Bearer "
                            "{{ $('Datos API Cuenta objetivo - SUCURSAL').item.json['Token/API'] }}"
                        ),
                    },
                    {"name": "Content-Type", "value": "application/json"},
                ]
            },
            "sendBody": True,
            "specifyBody": "json",
            "jsonBody": json_body,
            "options": {"redirect": {"redirect": {}}},
        },
        "type": "n8n-nodes-base.httpRequest",
        "typeVersion": 4.2,
        "position": [4368, 384],
        "id": str(uuid.uuid4()),
        "name": NAME_PUT_SUC,
        "onError": "continueRegularOutput",
        "notes": "Autoref: setea CF en sucursal = su propio contact.id.",
    }


def parse_args():
    ap = argparse.ArgumentParser()
    ap.add_argument("--apply", action="store_true",
                    help="Aplicar PUT real (default: dry-run a n8n/dryrun_*.json)")
    return ap.parse_args()


def main():
    args = parse_args()
    api_key, base_url = load_credentials()
    client = N8NClient(api_key, base_url)

    print(f"[1/6] GET workflow {WID}")
    wf = client.get_workflow(WID)
    print(f"      versionId previo: {wf.get('versionId')}")
    print(f"      active          : {wf.get('active')}")
    print(f"      total nodos     : {len(wf.get('nodes') or [])}")

    existing = {n["name"] for n in wf.get("nodes") or []}
    for needed_existing in [SRC_TERMINAL, "Extraer id_contacto_sucursal de Marca",
                            "Webhook", "Datos API Cuenta Origen",
                            "Datos API Cuenta objetivo - SUCURSAL",
                            "Conseguir Custom Cuenta objetivo - SUCURSAL",
                            "Obtener datos completos de Contacto objetivo - SUCURSAL"]:
        if needed_existing not in existing:
            print(f"\nERROR: falta nodo requerido {needed_existing!r}. Abortando.")
            sys.exit(2)
    for new_name in [NAME_IF, NAME_PUT_MARCA, NAME_PUT_SUC]:
        if new_name in existing:
            print(f"\nERROR: nodo {new_name!r} ya existe. Abortando para no duplicar.")
            sys.exit(2)

    print(f"\n[2/6] Backup fresco")
    _, bpath = client.backup_workflow(WID, label="pre_fallback_post_update")
    print(f"      backup -> {bpath}")

    print(f"\n[3/6] Inyectar IF + 2 PUTs")
    if_node = build_if_node()
    put_marca = build_put_marca()
    put_suc = build_put_sucursal()
    client.add_node(wf, if_node)
    client.add_node(wf, put_marca)
    client.add_node(wf, put_suc)
    print(f"      IF       : {NAME_IF}")
    print(f"      PUT Marca: {NAME_PUT_MARCA}")
    print(f"      PUT Suc  : {NAME_PUT_SUC}")

    print(f"\n[4/6] Reconectar grafo")
    conns = wf["connections"]
    # SRC_TERMINAL -> IF
    conns[SRC_TERMINAL] = {"main": [[{"node": NAME_IF, "type": "main", "index": 0}]]}
    # IF [true]=output0 -> PUT_MARCA; IF [false]=output1 -> nada (branch vacio, no None)
    conns[NAME_IF] = {
        "main": [
            [{"node": NAME_PUT_MARCA, "type": "main", "index": 0}],  # true
            [],  # false: sin destino
        ]
    }
    # PUT_MARCA -> PUT_SUC
    conns[NAME_PUT_MARCA] = {"main": [[{"node": NAME_PUT_SUC, "type": "main", "index": 0}]]}
    # PUT_SUC -> (terminal)
    print(f"      {SRC_TERMINAL} -> {NAME_IF}")
    print(f"      {NAME_IF} [true]  -> {NAME_PUT_MARCA}")
    print(f"      {NAME_IF} [false] -> (fin)")
    print(f"      {NAME_PUT_MARCA} -> {NAME_PUT_SUC}")
    print(f"      {NAME_PUT_SUC} -> (fin)")

    print(f"\n[5/6] {'APPLY' if args.apply else 'DRY-RUN'} put_workflow")
    result = client.put_workflow(WID, wf, dry_run=not args.apply)
    if not args.apply:
        print(f"      dry-run dump -> {result}")
        print("\nLISTO. Revisa el JSON. Si todo bien, corre con --apply.")
        return

    print(f"\n[6/6] Verificar y reactivar")
    new_wf = client.verify_post(
        WID,
        expected_node_names=[NAME_IF, NAME_PUT_MARCA, NAME_PUT_SUC],
        prev_version_id=wf.get("versionId"),
    )
    print(f"      versionId nuevo: {new_wf.get('versionId')}")
    if not new_wf.get("active"):
        print("      workflow inactivo tras PUT; reactivando...")
        client.activate(WID)
        new_wf = client.get_workflow(WID)
    print(f"      active final   : {new_wf.get('active')}")
    print(f"      total nodos    : {len(new_wf.get('nodes') or [])}")
    print("\nOK.")


if __name__ == "__main__":
    main()
