#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Fase 1 FIX: el nodo `Buscar Contacto Objetivo - MARCA (phone)` referenciaba
`$json['Token/API']` y `$json['Location ID']` asumiendo que el input previo era
`Datos API Cuenta objetivo - MARCA`. Tras la Fase 1, el input proviene del IF
nuevo (que solo trae `contacts` y `total`). Cambiamos las refs a explícitas.

Idempotente.
"""
import argparse
import json
import os
import sys

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, ROOT)
sys.path.insert(0, os.path.join(ROOT, "scripts"))
from n8n_workflow_lib import load_credentials, N8NClient  # noqa: E402

WID = "x4DqZ5FtSc43tdzB"
TARGET_NODE = "Buscar Contacto Objetivo - MARCA (phone)"


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--apply", action="store_true")
    args = parser.parse_args()
    if hasattr(sys.stdout, "reconfigure"):
        sys.stdout.reconfigure(encoding="utf-8")

    client = N8NClient(*load_credentials())
    wf, backup_path = client.backup_workflow(WID, label="fase1_fix_phone_refs")
    print(f"backup: {backup_path}")
    prev = wf.get("versionId")

    node = client.find_node(wf, TARGET_NODE)
    if not node:
        raise SystemExit(f"nodo {TARGET_NODE!r} no encontrado")

    p = node["parameters"]
    # Cambiar Authorization header
    for h in p.get("headerParameters", {}).get("parameters", []):
        if h.get("name") == "Authorization":
            old = h["value"]
            new = old.replace(
                "$json['Token/API']",
                "$('Datos API Cuenta objetivo - MARCA').item.json['Token/API']"
            )
            if old != new:
                h["value"] = new
                print(f"  Authorization: actualizado")
            else:
                print(f"  Authorization: ya tenía referencia explícita (skip)")

    # Cambiar jsonBody locationId
    body = p.get("jsonBody") or ""
    new_body = body.replace(
        "$json['Location ID']",
        "$('Datos API Cuenta objetivo - MARCA').item.json['Location ID']"
    )
    if new_body != body:
        p["jsonBody"] = new_body
        print(f"  jsonBody locationId: actualizado")
    else:
        print(f"  jsonBody locationId: ya tenía referencia explícita (skip)")

    # Dry-run / apply
    if not args.apply:
        res = client.put_workflow(WID, wf, dry_run=True)
        print(f"DRY-RUN. path: {res['path']}")
        return

    client.put_workflow(WID, wf, dry_run=False)
    wf2 = client.verify_post(WID, expected_node_names=[TARGET_NODE], prev_version_id=prev)
    print(f"versionId nuevo: {wf2.get('versionId')}")
    print(f"active: {wf2.get('active')}")
    if not wf2.get("active"):
        client.activate(WID)
        print("activado.")
    print("OK")


if __name__ == "__main__":
    main()
