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 round_trip_test(ce_id):
    print(f"--- Starting Round-Trip POC: CE-ID {ce_id} -> SuperOffice ---")
    
    # 1. Get enriched data from Company Explorer
    ce_data = get_company_details(ce_id)
    if not ce_data or "error" in ce_data:
        print(f"❌ ERROR: Could not fetch data from Company Explorer for ID {ce_id}")
        return

    print(f"✅ Success: Received data from CE for '{ce_data.get('name')}'")
    
    # 2. Extract CRM ID
    so_id = ce_data.get("crm_id")
    if not so_id:
        print("❌ ERROR: No crm_id found in Company Explorer for this record. Cannot sync back.")
        return
    
    print(f"Targeting SuperOffice Contact ID: {so_id}")

    # 3. Prepare SuperOffice Update Payload
    # Based on your request: Address, Website, Email, Phone
    # Note: We need to match the SO schema (Street Address vs Postal Address)
    so_payload = {
        "Name": ce_data.get("name"),
        "UrlAddress": ce_data.get("website"),
        "Address": {
            "Street": {
                "Address1": ce_data.get("address", ""), # Simplified mapping for POC
                "City": ce_data.get("city", ""),
                "Zipcode": ce_data.get("zip", "")
            }
        }
    }
    
    # 4. Perform Update via SuperOfficeClient
    client = SuperOfficeClient()
    print(f"Updating SuperOffice Contact {so_id}...")
    
    # Using the generic PUT method from our client
    endpoint = f"Contact/{so_id}"
    result = client._put(endpoint, so_payload)
    
    if result:
        print(f"🚀 SUCCESS! Round-trip complete. SuperOffice Contact {so_id} updated.")
        print(f"Updated Data: {ce_data.get('website')} | {ce_data.get('city')}")
    else:
        print("❌ ERROR: Failed to update SuperOffice.")

if __name__ == "__main__":
    # Test with the ID you manually enriched
    round_trip_test(53)
