
import sys
import os
import json
import traceback
from dotenv import load_dotenv

# Explicitly load .env from the project root
dotenv_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '.env'))
load_dotenv(dotenv_path=dotenv_path, override=True)

sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from superoffice_client import SuperOfficeClient
from config import settings

def get_enriched_data(contact_id: int):
    print(f"🚀 [DEBUG] Starting fetch for ContactId: {contact_id}")
    try:
        client = SuperOfficeClient()
        if not client.access_token:
            print("❌ Authentication failed.")
            return

        print("✅ [DEBUG] Client authenticated.")
        
        try:
            contact_data = client.get_contact(
                contact_id,
                select=[
                    "Name", "UrlAddress", "OrgNr", "UserDefinedFields"
                ]
            )
            print(f"✅ [DEBUG] API Call successful. Data type: {type(contact_data)}")
        except Exception as e:
            print(f"❌ [DEBUG] API Call failed: {e}")
            traceback.print_exc()
            return

        if not contact_data:
            print("❌ [DEBUG] No data returned.")
            return

        print(f"✅ [DEBUG] Name: {contact_data.get('Name')}")

        try:
            udfs = contact_data.get("UserDefinedFields", {})
            print(f"✅ [DEBUG] UDFs extracted. Type: {type(udfs)}")
        except Exception as e:
            print(f"❌ [DEBUG] Failed to extract UDFs: {e}")
            traceback.print_exc()
            return

        if isinstance(udfs, dict):
            print(f"✅ [DEBUG] UDFs is a dict with {len(udfs)} keys.")
            try:
                # Iterate keys safely
                print("--- UDF KEYS SAMPLE ---")
                for k in list(udfs.keys())[:5]:
                    print(f"Key: {k} (Type: {type(k)})")
            except Exception as e:
                print(f"❌ [DEBUG] Failed to iterate keys: {e}")
                traceback.print_exc()

        # Try to access specific key
        target_key = settings.UDF_VERTICAL
        print(f"✅ [DEBUG] Attempting access with key: '{target_key}' (Type: {type(target_key)})")
        
        try:
            if target_key in udfs:
                val = udfs[target_key]
                print(f"✅ [DEBUG] Value found: {val}")
            else:
                print(f"ℹ️ [DEBUG] Key not found in UDFs.")
        except Exception as e:
            print(f"❌ [DEBUG] Failed to access dictionary with key: {e}")
            traceback.print_exc()

    except Exception as e:
        print(f"❌ [DEBUG] Global Error: {e}")
        traceback.print_exc()

if __name__ == "__main__":
    target_contact_id = 171185 
    get_enriched_data(target_contact_id)
