import sys
import os
from dotenv import load_dotenv

# Explicitly load .env from the parent directory
dotenv_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '.env'))
print(f"Loading .env from: {dotenv_path}")
load_dotenv(dotenv_path=dotenv_path, override=True)

sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from superoffice_client import SuperOfficeClient
def create_test_company():
    """
    Creates a new company in SuperOffice for E2E testing.
    """
    company_name = "Bremer Abenteuerland"
    # Provide a real-world, scrapable website to test enrichment
    website = "https://www.belantis.de/"
    print(f"🚀 Attempting to create company: '{company_name}'")
    try:
        client = SuperOfficeClient()
        if not client.access_token:
            print("❌ Authentication failed. Check your .env file.")
            return
        # Check if company already exists
        existing = client.search(f"Contact?$select=contactId,name&$filter=name eq '{company_name}'")
        print(f"DEBUG: Raw search response: {existing}")
        if existing:
            contact_id = existing[0]['contactId']
            print(f"⚠️ Company '{company_name}' already exists with ContactId: {contact_id}.")
            print("Skipping creation.")
            return contact_id
        payload = {
            "Name": company_name,
            "Urls": [
                {
                    "Value": website,
                    "Description": "Main Website"
                }
            ],
            "Country": {
                "CountryId": 68 # Germany
            }
        }
        new_company = client._post("Contact", payload)
        if new_company and "contactId" in new_company:
            contact_id = new_company["contactId"]
            print(f"✅ SUCCESS! Created company '{company_name}' with ContactId: {contact_id}")
            return contact_id
        else:
            print(f"❌ Failed to create company. Response: {new_company}")
            return None
    except Exception as e:
        print(f"An error occurred: {e}")
        return None
if __name__ == "__main__":
    create_test_company()
