import os
import django
from django.conf import settings

import sys

# Add /app to sys.path so we can import myproject
sys.path.append('/app')

# Setup Django environment
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
django.setup()

from tenants.models import Client, Domain

def ensure_public_tenant():
    domain_name = os.environ.get('DOMAIN_NAME', 'localhost')
    print(f"Checking public tenant for domain: {domain_name}")
    
    email = os.environ.get('TENANT_ADMIN_EMAIL', 'admin@example.com')
    name = os.environ.get('TENANT_ADMIN_NAME', 'System Administrator')
    
    # 1. Ensure Client exists
    client, created = Client.objects.get_or_create(
        schema_name='public',
        defaults={
            'name': 'System Tenant',
            'owner_email': email,
            'owner_name': name
        }
    )
    if created:
        print("Created public tenant client.")
    else:
        print("Public tenant client already exists.")

    # 2. Ensure Domain exists
    # Check if this specific domain exists
    domain, created = Domain.objects.get_or_create(
        domain=domain_name,
        defaults={'tenant': client, 'is_primary': True}
    )
    
    if created:
        print(f"Created domain {domain_name} for public tenant.")
    else:
        print(f"Domain {domain_name} already exists.")
        if domain.tenant != client:
            print(f"WARNING: Domain {domain_name} is assigned to another tenant!")

    # 3. Init system data (System Customer, etc.)
    # SKIP for public tenant as it doesn't have these tables (they separate in tenant schemas)
    # print("Initializing system data for public tenant...")
    # from django.core.management import call_command
    # try:
    #     call_command('init_tenant_data', schema='public')
    # except Exception as e:
    #     print(f"Error initializing system data: {e}")

if __name__ == '__main__':
    ensure_public_tenant()
