import os
import json
import sys
from dotenv import load_dotenv

# Path gymnastics
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "connector-superoffice"))

from company_explorer_connector import get_company_details
from superoffice_client import SuperOfficeClient

# Load ENV
load_dotenv(dotenv_path="/home/node/clawd/.env", override=True)

def perform_final_round_trip(ce_id):
    client = SuperOfficeClient()
    print(f"--- Final Round-Trip: CE {ce_id} -> SuperOffice ---")
    
    # 1. Get enriched data from CE
    ce_data = get_company_details(ce_id)
    if not ce_data or "error" in ce_data:
        print("❌ Could not fetch CE data.")
        return
    
    so_id = ce_data.get("crm_id")
    if not so_id:
        print("❌ No SO ID found in CE.")
        return

    # 2. Fetch current SO contact
    contact = client._get(f"Contact/{so_id}")
    if not contact:
        print(f"❌ Could not fetch SO Contact {so_id}")
        return

    # 3. Intelligent Mapping (Full Object)
    print(f"Mapping data for {ce_data.get('name')}...")
    
    # Simple Fields
    contact["UrlAddress"] = ce_data.get("website", "")
    contact["Department"] = "KI-Enriched via CE"
    
    # Address Object
    if "Address" not in contact: contact["Address"] = {}
    if "Street" not in contact["Address"]: contact["Address"]["Street"] = {}
    
    contact["Address"]["Street"]["Address1"] = ce_data.get("address", "")
    contact["Address"]["Street"]["City"] = ce_data.get("city", "")
    contact["Address"]["Street"]["Zipcode"] = ce_data.get("zip", "")
    
    # Phones (List)
    if ce_data.get("phone"):
        contact["Phones"] = [{"Number": ce_data.get("phone"), "Description": "Main"}]

    # 4. Write back
    print(f"Sending full update to SO Contact {so_id}...")
    result = client._put(f"Contact/{so_id}", contact)
    
    if result:
        print("🚀 SUCCESS! Round-trip for Robo-Planet complete.")
        print(f"Website: {contact['UrlAddress']}")
        print(f"City: {contact['Address']['Street']['City']}")
    else:
        print("❌ Update failed.")

if __name__ == "__main__":
    perform_final_round_trip(53)
