import os
import sys
import django

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.base")
django.setup()

from apps.integrations.models import IntegrationProvider, IntegrationModule, ProviderStatus
from apps.integrations.services import IntegrationService
from apps.organizations.models import Organization

def main():
    org = Organization.objects.first()

    provider, created = IntegrationProvider.objects.get_or_create(
        name="PREPOC Website",
        organization=org,
        defaults={
            "provider_type": "WEBSITE",
            "base_url": "http://localhost:3000",
            "is_active": True,
            "api_key": "your-long-random-secret"
        }
    )
    if not created:
        provider.base_url = "http://localhost:3000"
        provider.api_key = "your-long-random-secret"
        provider.save()
        
    print(f"Provider created/updated: {provider.name}")
    
    module, m_created = IntegrationModule.objects.get_or_create(
        provider=provider,
        module_key="contact-submissions",
        organization=org,
        defaults={
            "display_name": "Contact Submissions",
            "endpoint": "/api/integrations/contact-submissions",
            "target_module": "crm",
            "target_model": "Lead",
            "enabled": True,
            "sync_order": 1
        }
    )
    
    print(f"Module created/updated: {module.display_name}")
    
    print("\n--- Testing Connection ---")
    health = IntegrationService.test_connection(provider)
    print(f"Health Result: {health}")
    
    if health.get("status") == "CONNECTED":
        print("\n--- Triggering Sync ---")
        IntegrationService.sync_provider(provider)
        print("Sync completed. Check Integration Logs and Payloads in DB.")
        
        from apps.integrations.models import IntegrationLog
        log = IntegrationLog.objects.filter(provider=provider).order_by('-created_at').first()
        if log:
            print(f"Latest Log: {log.status}, Imported: {log.records_imported}, Failed: {log.failed}")
    else:
        print("Connection failed. Cannot sync.")

if __name__ == "__main__":
    main()
