import os
import json
import sys
from dotenv import load_dotenv

# Path gymnastics to ensure imports work from the current directory
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 handle_company_workflow
from superoffice_client import SuperOfficeClient

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

def sync_roboplanet():
    print("--- Starting Sync Test: SuperOffice -> Company Explorer ---")
    
    # 1. Fetch Contact from SuperOffice
    client = SuperOfficeClient()
    contact_id = 2
    print(f"Fetching Contact ID {contact_id} from SuperOffice...")
    contact_so = client._get(f"Contact/{contact_id}")
    
    if not contact_so:
        print("❌ ERROR: Could not find Contact ID 2 in SuperOffice.")
        return

    company_name = contact_so.get("Name")
    print(f"✅ Success: Found '{company_name}' in SuperOffice.")

    # 2. Push to Company Explorer
    print(f"\nPushing '{company_name}' to Company Explorer via Connector...")
    # Using the workflow to check existence and create if needed
    result = handle_company_workflow(company_name)
    
    print("\n--- WORKFLOW RESULT ---")
    print(json.dumps(result, indent=2, ensure_ascii=False))

if __name__ == "__main__":
    sync_roboplanet()
