import os
import json
import sys
import requests
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 superoffice_client import SuperOfficeClient
from company_explorer_connector import get_company_details

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

def full_enrichment_writeback(ce_id):
    client = SuperOfficeClient()
    print(f"--- Full Enrichment Write-Back: CE {ce_id} -> SuperOffice ---")
    
    # 1. Get 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. Build Surgical Payload (Postal Address, VAT, Vertical)
    # We use the specific sub-object structure SO expects
    payload = {
        "contactId": int(so_id),
        "OrgNr": "DE348572190", # Test VAT
        "Department": "Fully Enriched 13:25",
        "Address": {
            "Postal": {
                "Address1": ce_data.get("address", "Humboldtstr. 1"),
                "City": ce_data.get("city", "Dornstadt"),
                "Zipcode": ce_data.get("zip", "89160")
            }
        },
        "UserDefinedFields": {
            "SuperOffice:5": "[I:23]" # Vertical: Logistics - Warehouse
        }
    }
    
    url = f"{client.base_url}/Contact/{so_id}"
    print(f"Sending Full Payload to {url}...")
    
    resp = requests.put(url, headers=client.headers, json=payload)
    
    print(f"Status Code: {resp.status_code}")
    if resp.status_code == 200:
        print("🚀 SUCCESS! Full enrichment (Address, VAT, Vertical) should be visible.")
    else:
        print(f"❌ Error: {resp.text}")

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