#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Investigacion read-only: opp de Marca hNPaauyuqM1Epycwj0wj (ERIKA RUBI CONCHA).
Imprime CF resueltos, contactId, link a sucursal y busca el contacto en sucursales."""
import os, sys
ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if ROOT_DIR not in sys.path:
    sys.path.insert(0, ROOT_DIR)
import sync_engine
from scripts import common

gc = sync_engine.ghl_client
BRAND = common.BRAND_LOCATION_ID
OPP_ID = "hNPaauyuqM1Epycwj0wj"

accounts = {a["location_id"]: a for a in common.load_accounts()}
brand_token = accounts[BRAND]["token"]


def keymap(token, loc, obj):
    fields = gc.get_object_schema_fields(token, loc, obj)
    return {f["id"]: f.get("fieldKey") for f in fields if f.get("id")}


def cfval(cf):
    for k in ("fieldValue", "fieldValueString", "value"):
        if cf.get(k) is not None:
            return cf[k]
    return None


opp = (gc.get_opportunity(brand_token, OPP_ID) or {}).get("opportunity") or {}
print("=== OPP MARCA ===")
print("name:", opp.get("name"))
print("status:", opp.get("status"), "value:", opp.get("monetaryValue"))
print("contactId:", opp.get("contactId") or (opp.get("contact") or {}).get("id"))
id2key = keymap(brand_token, BRAND, "opportunity")
print("--- customFields (opp Marca) ---")
link = None
for cf in opp.get("customFields") or []:
    k = id2key.get(cf.get("id"))
    v = cfval(cf)
    print(f"  {k} = {v!r}")
    if k == "opportunity.id_oportunidad_sucursal":
        link = v
print("LINK id_oportunidad_sucursal:", link)

# contacto de Marca
cid = opp.get("contactId") or (opp.get("contact") or {}).get("id")
if cid:
    c = (gc._request("GET", f"/contacts/{cid}", brand_token) or {}).get("contact") or {}
    print("\n=== CONTACTO MARCA ===")
    print("name:", c.get("contactName") or f"{c.get('firstName')} {c.get('lastName')}")
    print("phone:", c.get("phone"), "email:", c.get("email"))
    ck = keymap(brand_token, BRAND, "contact")
    for cf in c.get("customFields") or []:
        k = ck.get(cf.get("id"))
        if k in ("contact.id_contacto_sucursal", "contact.sucursal", "contact.tienda",
                 "contact.fuente_de_posible_cliente", "contact.fuente_de_prospecto"):
            print(f"  {k} = {cf.get('value')!r}")

# buscar la opp link en cada sucursal para identificar la sucursal de origen
if link:
    print("\n=== BUSCANDO opp", link, "EN SUCURSALES ===")
    for loc, acc in accounts.items():
        if loc == BRAND or acc.get("type") == "brand":
            continue
        try:
            bo = (gc.get_opportunity(acc["token"], link) or {}).get("opportunity") or {}
        except Exception:
            bo = {}
        if bo:
            print(f"  ENCONTRADA en {acc['nombre']} ({loc})")
            bk = keymap(acc["token"], loc, "opportunity")
            for cf in bo.get("customFields") or []:
                k = bk.get(cf.get("id"))
                if k in ("opportunity.sucursal", "opportunity.tienda",
                         "opportunity.fuente_de_posible_cliente", "opportunity.fuente_de_prospecto"):
                    print(f"      {k} = {cfval(cf)!r}")
            break
    else:
        print("  No encontrada por GET directo en ninguna sucursal.")
