#!/usr/bin/env python
"""
Script to create 3 real users with 3 paid packages (Starter, Growth, Scale)
All accounts will be active and properly configured.
Email format: plan-name@igny8.com
"""
import os
import django
import sys
from decimal import Decimal

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

from django.db import transaction
from igny8_core.auth.models import Plan, Account, User
from django.utils.text import slugify

# User data - 3 users with 3 different paid plans
# Email format: plan-name@igny8.com
USERS_DATA = [
    {
        "email": "starter@igny8.com",
        "username": "starter",
        "first_name": "Starter",
        "last_name": "Account",
        "password": "SecurePass123!@#",
        "plan_slug": "starter",  # $89/month
        "account_name": "Starter Account",
    },
    {
        "email": "growth@igny8.com",
        "username": "growth",
        "first_name": "Growth",
        "last_name": "Account",
        "password": "SecurePass123!@#",
        "plan_slug": "growth",  # $139/month
        "account_name": "Growth Account",
    },
    {
        "email": "scale@igny8.com",
        "username": "scale",
        "first_name": "Scale",
        "last_name": "Account",
        "password": "SecurePass123!@#",
        "plan_slug": "scale",  # $229/month
        "account_name": "Scale Account",
    },
]


def create_user_with_plan(user_data):
    """Create a user with account and assigned plan."""
    try:
        with transaction.atomic():
            # Get the plan
            try:
                plan = Plan.objects.get(slug=user_data['plan_slug'], is_active=True)
            except Plan.DoesNotExist:
                print(f"❌ ERROR: Plan '{user_data['plan_slug']}' not found or inactive!")
                return None
            
            # Check if user already exists
            if User.objects.filter(email=user_data['email']).exists():
                print(f"⚠️  User {user_data['email']} already exists. Updating...")
                existing_user = User.objects.get(email=user_data['email'])
                if existing_user.account:
                    existing_user.account.plan = plan
                    existing_user.account.status = 'active'
                    existing_user.account.save()
                    print(f"   ✅ Updated account plan to {plan.name} and set status to active")
                return existing_user
            
            # Generate unique account slug
            base_slug = slugify(user_data['account_name'])
            account_slug = base_slug
            counter = 1
            while Account.objects.filter(slug=account_slug).exists():
                account_slug = f"{base_slug}-{counter}"
                counter += 1
            
            # Create user first (without account)
            user = User.objects.create_user(
                username=user_data['username'],
                email=user_data['email'],
                password=user_data['password'],
                first_name=user_data['first_name'],
                last_name=user_data['last_name'],
                account=None,  # Will be set after account creation
                role='owner'
            )
            
            # Create account with user as owner and assigned plan
            account = Account.objects.create(
                name=user_data['account_name'],
                slug=account_slug,
                owner=user,
                plan=plan,
                status='active',  # Set to active
                credits=plan.included_credits or 0,  # Set initial credits from plan
            )
            
            # Update user to reference the new account
            user.account = account
            user.save()
            
            print(f"✅ Created user: {user.email}")
            print(f"   - Name: {user.get_full_name()}")
            print(f"   - Username: {user.username}")
            print(f"   - Account: {account.name} (slug: {account.slug})")
            print(f"   - Plan: {plan.name} (${plan.price}/month)")
            print(f"   - Status: {account.status}")
            print(f"   - Credits: {account.credits}")
            print(f"   - Max Sites: {plan.max_sites}")
            print(f"   - Max Users: {plan.max_users}")
            print()
            
            return user
            
    except Exception as e:
        print(f"❌ ERROR creating user {user_data['email']}: {e}")
        import traceback
        traceback.print_exc()
        return None


def main():
    """Main function to create all users."""
    print("=" * 80)
    print("Creating 3 Users with Paid Plans")
    print("=" * 80)
    print()
    
    # Verify plans exist
    print("Checking available plans...")
    plans = Plan.objects.filter(is_active=True).order_by('price')
    if plans.count() < 3:
        print(f"⚠️  WARNING: Only {plans.count()} active plan(s) found. Need at least 3.")
        print("Available plans:")
        for p in plans:
            print(f"   - {p.slug} (${p.price})")
        print()
        print("Please run import_plans.py first to create the plans.")
        return
    
    print("✅ Found plans:")
    for p in plans:
        print(f"   - {p.name} ({p.slug}): ${p.price}/month")
    print()
    
    # Create users
    created_users = []
    for user_data in USERS_DATA:
        user = create_user_with_plan(user_data)
        if user:
            created_users.append(user)
    
    # Summary
    print("=" * 80)
    print("SUMMARY")
    print("=" * 80)
    print(f"Total users created/updated: {len(created_users)}")
    print()
    print("User Login Credentials:")
    print("-" * 80)
    for user_data in USERS_DATA:
        print(f"Email: {user_data['email']}")
        print(f"Password: {user_data['password']}")
        print(f"Plan: {user_data['plan_slug'].title()}")
        print()
    
    print("✅ All users created successfully!")
    print()
    print("You can now log in with any of these accounts at:")
    print("https://app.igny8.com/login")


if __name__ == '__main__':
    try:
        main()
    except Exception as e:
        print(f"❌ Fatal error: {e}", file=sys.stderr)
        import traceback
        traceback.print_exc()
        sys.exit(1)

