import os
import django

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

from django.contrib.auth.models import User
from core.models import Company, Profile, AIConfiguration
from core.utils import encrypt_value

def setup_demo():
    # 1. Get or create demo company
    company, _ = Company.objects.get_or_create(
        tenant_id='telecom-corp',
        defaults={'name': 'Telecom Corp'}
    )

    # 2. Get or create admin user
    user = User.objects.filter(username='admin').first()
    if not user:
        user = User.objects.create_superuser('admin', 'admin@example.com', 'admin123')
    
    # 3. Ensure user has a profile with the correct company
    profile, created = Profile.objects.get_or_create(
        user=user,
        defaults={'company': company, 'role': 'admin'}
    )
    if not created and profile.company != company:
        print(f"Updating {user.username}'s company from {profile.company.name} to {company.name}")
        profile.company = company
        profile.save()

    # 4. Add AI Configurations
    providers = [
        ('openai', 'sk-proj-demo-12345'),
        ('perplexity', 'pplx-demo-67890'),
        ('merlin', 'merlin-free-tier-key'),
        ('poe', 'pb-poe-access-token'),
        ('openrouter', 'sk-or-v1-free-key')
    ]

    for provider, key in providers:
        encrypted_key = encrypt_value(key)
        AIConfiguration.objects.update_or_create(
            company=company,
            provider=provider,
            defaults={'api_key': encrypted_key, 'is_active': True}
        )

    print("Demo setup complete. Added OpenAI, Perplexity, Merlin AI, POE, and OpenRouter configurations.")

if __name__ == "__main__":
    setup_demo()