import sys
import os
import os
import sys
from dotenv import load_dotenv

# Load .env BEFORE importing SuperOfficeClient to ensure settings are correctly initialized
load_dotenv(os.path.join(os.path.dirname(__file__), "../.env"), override=True)

from superoffice_client import SuperOfficeClient

# Configuration
WEBHOOK_NAME = "Gemini Connector Production"
TARGET_URL = f"https://floke-ai.duckdns.org/connector/webhook?token={os.getenv('WEBHOOK_TOKEN')}"
EVENTS = [
    "contact.created",
    "contact.changed",
    "person.created",
    "person.changed"
]

def register():
    print(f"🚀 Initializing SuperOffice Client for Production...")
    try:
        client = SuperOfficeClient()
    except Exception as e:
        print(f"❌ Failed to connect: {e}")
        return

    if not client.access_token:
        print("❌ Auth failed. Check SO_CLIENT_ID and SO_REFRESH_TOKEN in .env")
        return

    print("🔎 Checking existing webhooks...")
    webhooks = client._get("Webhook")
    
    if webhooks and 'value' in webhooks:
        for wh in webhooks['value']:
            if wh['Name'] == WEBHOOK_NAME:
                print(f"⚠️  Webhook '{WEBHOOK_NAME}' already exists (ID: {wh['WebhookId']}).")
                
                # Check if URL matches
                if wh['TargetUrl'] != TARGET_URL:
                    print(f"   ⚠️ URL Mismatch!")
                    print(f"   Existing: {wh['TargetUrl']}")
                    print(f"   New:      {TARGET_URL}")
                    print("   Please delete it manually via API or extend client.")
                else:
                    print(f"   ✅ Webhook is up to date.")
                    if wh['State'] != 'Active':
                        print(f"   ⚠️ Webhook is '{wh['State']}'. Reactivating...")
                        res = client._put(f"Webhook/{wh['WebhookId']}", {"State": "Active"})
                        if res:
                            print(f"   ✅ Webhook reactivated.")
                        else:
                            print(f"   ❌ Failed to reactivate webhook.")
                return

    print(f"✨ Registering new webhook: {WEBHOOK_NAME}")
    
    webhook_secret = os.getenv('WEBHOOK_SECRET')
    if not webhook_secret:
        print("❌ Error: WEBHOOK_SECRET missing in .env")
        return

    payload = {
        "Name": WEBHOOK_NAME,
        "Events": EVENTS,
        "TargetUrl": TARGET_URL,
        "Secret": webhook_secret, # Used for signature calculation by SO
        "State": "Active",
        "Type": "Webhook"
    }

    try:
        # Note: _post is defined in your client, returns JSON
        res = client._post("Webhook", payload)
        if res and "WebhookId" in res:
            print(f"✅ SUCCESS! Webhook created with ID: {res['WebhookId']}")
            print(f"   Target: {res['TargetUrl']}")
        else:
            print(f"❌ Creation failed. Response: {res}")
    except Exception as e:
        print(f"❌ Error during registration: {e}")

if __name__ == "__main__":
    register()
