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

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

def force_write(so_id):
    client = SuperOfficeClient()
    print(f"--- Force Write-Back: Contact {so_id} ---")
    
    # Using the mandatory fields you identified and the structured address
    payload = {
        "contactId": int(so_id),
        "Name": "RoboPlanet GmbH-SOD",
        "Number2": "123", # Mandatory field fix
        "OrgNr": "DE348572190",
        "Department": "Force Write 13:35",
        "Address": {
            "Postal": {
                "Address1": "Humboldtstr. 1",
                "City": "Dornstadt",
                "Zipcode": "89160"
            },
            "Street": {
                "Address1": "Humboldtstr. 1",
                "City": "Dornstadt",
                "Zipcode": "89160"
            }
        },
        "UserDefinedFields": {
            "SuperOffice:5": "[I:23]" # Vertical: Logistics
        }
    }
    
    url = f"{client.base_url}/Contact/{so_id}"
    print(f"Sending Force 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! Check Address, VAT and Vertical now.")
    else:
        print(f"❌ Error: {resp.text}")

if __name__ == "__main__":
    force_write(2)
