#!/usr/bin/env python3
"""
Script to ensure admin user is properly configured.
Run this after database initialization.
"""
import asyncio
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).parent.parent))

from sqlalchemy import select, update
from app.database import AsyncSessionLocal
from app.models.user import User
from app.models.subscription import Subscription, SubscriptionTier, SubscriptionStatus, TIER_CONFIG


ADMIN_EMAIL = "guggeryves@hotmail.com"


async def verify_admin():
    """Ensure admin user exists and is properly configured."""
    print(f"🔍 Looking for user: {ADMIN_EMAIL}")
    
    async with AsyncSessionLocal() as db:
        # Find user
        result = await db.execute(
            select(User).where(User.email == ADMIN_EMAIL)
        )
        user = result.scalar_one_or_none()
        
        if not user:
            print(f"❌ User not found: {ADMIN_EMAIL}")
            print("   Please register first, then run this script again.")
            return False
        
        print(f"✅ User found: ID={user.id}, Name={user.name}")
        
        # Update user flags
        changes = []
        
        if not user.is_admin:
            user.is_admin = True
            changes.append("is_admin = True")
        
        if not user.is_verified:
            user.is_verified = True
            changes.append("is_verified = True")
        
        if not user.is_active:
            user.is_active = True
            changes.append("is_active = True")
        
        if changes:
            await db.commit()
            print(f"✅ Updated user: {', '.join(changes)}")
        else:
            print("✅ User already has correct flags")
        
        # Check subscription
        sub_result = await db.execute(
            select(Subscription).where(Subscription.user_id == user.id)
        )
        subscription = sub_result.scalar_one_or_none()
        
        if not subscription:
            # Create Tycoon subscription
            tycoon_config = TIER_CONFIG.get(SubscriptionTier.TYCOON, {})
            subscription = Subscription(
                user_id=user.id,
                tier=SubscriptionTier.TYCOON,
                status=SubscriptionStatus.ACTIVE,
                max_domains=tycoon_config.get("domain_limit", 500),
            )
            db.add(subscription)
            await db.commit()
            print("✅ Created Tycoon subscription")
        elif subscription.tier != SubscriptionTier.TYCOON:
            subscription.tier = SubscriptionTier.TYCOON
            subscription.status = SubscriptionStatus.ACTIVE
            subscription.max_domains = TIER_CONFIG.get(SubscriptionTier.TYCOON, {}).get("domain_limit", 500)
            await db.commit()
            print("✅ Upgraded to Tycoon subscription")
        else:
            print(f"✅ Subscription: {subscription.tier.value} (Active)")
        
        # Final status
        print("\n" + "="*50)
        print("📋 FINAL STATUS:")
        print(f"   Email:      {user.email}")
        print(f"   Name:       {user.name}")
        print(f"   Admin:      {'✅ Yes' if user.is_admin else '❌ No'}")
        print(f"   Verified:   {'✅ Yes' if user.is_verified else '❌ No'}")
        print(f"   Active:     {'✅ Yes' if user.is_active else '❌ No'}")
        print(f"   Tier:       Tycoon")
        print("="*50)
        print("\n✅ Admin user is ready! You can now login.")
        
        return True


if __name__ == "__main__":
    asyncio.run(verify_admin())

