"""
Initialize database for spread betting system
Creates tables and seeds with admin user and sample data
"""
import asyncio
from datetime import datetime, timedelta
from decimal import Decimal
from sqlalchemy import select

from app.database import engine, Base, async_session
from app.models import (
    User, Wallet, SportEvent, AdminSettings,
    SportType, EventStatus
)
from app.utils.security import get_password_hash


async def init_database():
    """Drop all tables and recreate"""
    print("🗑️  Dropping all tables...")
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.drop_all)

    print("📦 Creating all tables...")
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all)

    print("✅ Database tables created!")


async def seed_data():
    """Seed database with admin user and sample data"""
    async with async_session() as db:
        print("\n👤 Creating admin user...")

        # Create admin user
        admin = User(
            email="admin@h2h.com",
            username="admin",
            password_hash=get_password_hash("admin123"),
            display_name="H2H Admin",
            is_admin=True
        )
        db.add(admin)
        await db.flush()

        # Create admin wallet
        admin_wallet = Wallet(
            user_id=admin.id,
            balance=Decimal("10000.00"),
            escrow=Decimal("0.00"),
            currency="USD"
        )
        db.add(admin_wallet)

        print("✅ Admin user created")
        print("   📧 Email: admin@h2h.com")
        print("   🔑 Password: admin123")

        # Create test users
        print("\n👥 Creating test users...")

        alice = User(
            email="alice@example.com",
            username="alice",
            password_hash=get_password_hash("password123"),
            display_name="Alice"
        )
        db.add(alice)
        await db.flush()

        alice_wallet = Wallet(
            user_id=alice.id,
            balance=Decimal("1000.00"),
            escrow=Decimal("0.00")
        )
        db.add(alice_wallet)

        bob = User(
            email="bob@example.com",
            username="bob",
            password_hash=get_password_hash("password123"),
            display_name="Bob"
        )
        db.add(bob)
        await db.flush()

        bob_wallet = Wallet(
            user_id=bob.id,
            balance=Decimal("1000.00"),
            escrow=Decimal("0.00")
        )
        db.add(bob_wallet)

        charlie = User(
            email="charlie@example.com",
            username="charlie",
            password_hash=get_password_hash("password123"),
            display_name="Charlie"
        )
        db.add(charlie)
        await db.flush()

        charlie_wallet = Wallet(
            user_id=charlie.id,
            balance=Decimal("1000.00"),
            escrow=Decimal("0.00")
        )
        db.add(charlie_wallet)

        print("✅ Test users created")
        print("   alice@example.com / password123 ($1000)")
        print("   bob@example.com / password123 ($1000)")
        print("   charlie@example.com / password123 ($1000)")

        # Create admin settings
        print("\n⚙️  Creating admin settings...")

        settings = AdminSettings(
            default_house_commission_percent=Decimal("10.00"),
            default_min_bet_amount=Decimal("10.00"),
            default_max_bet_amount=Decimal("1000.00"),
            default_min_spread=-10.0,
            default_max_spread=10.0,
            spread_increment=0.5,
            platform_name="H2H Sports Betting",
            maintenance_mode=False
        )
        db.add(settings)

        print("✅ Admin settings created")
        print("   💰 House commission: 10%")
        print("   📊 Spread range: -10 to +10 (0.5 increments)")
        print("   💵 Bet limits: $10 - $1000")

        # Create sample sporting events
        print("\n🏈 Creating sample sporting events...")

        # Event 1: Wake Forest vs MS State (tonight)
        event1 = SportEvent(
            sport=SportType.FOOTBALL,
            home_team="Wake Forest",
            away_team="MS State",
            official_spread=3.0,
            game_time=datetime.utcnow() + timedelta(hours=8),
            venue="Truist Field",
            league="NCAA Football",
            min_spread=-10.0,
            max_spread=10.0,
            min_bet_amount=10.0,
            max_bet_amount=1000.0,
            created_by=admin.id,
            status=EventStatus.UPCOMING
        )
        db.add(event1)

        # Event 2: Lakers vs Celtics (tomorrow)
        event2 = SportEvent(
            sport=SportType.BASKETBALL,
            home_team="Los Angeles Lakers",
            away_team="Boston Celtics",
            official_spread=-5.5,
            game_time=datetime.utcnow() + timedelta(days=1, hours=3),
            venue="Crypto.com Arena",
            league="NBA",
            min_spread=-15.0,
            max_spread=15.0,
            min_bet_amount=10.0,
            max_bet_amount=1000.0,
            created_by=admin.id,
            status=EventStatus.UPCOMING
        )
        db.add(event2)

        # Event 3: Chiefs vs Bills (this weekend)
        event3 = SportEvent(
            sport=SportType.FOOTBALL,
            home_team="Kansas City Chiefs",
            away_team="Buffalo Bills",
            official_spread=-2.5,
            game_time=datetime.utcnow() + timedelta(days=3, hours=6),
            venue="Arrowhead Stadium",
            league="NFL",
            min_spread=-14.0,
            max_spread=14.0,
            min_bet_amount=25.0,
            max_bet_amount=2000.0,
            created_by=admin.id,
            status=EventStatus.UPCOMING
        )
        db.add(event3)

        await db.commit()

        print("✅ Sample events created")
        print("   🏈 Wake Forest vs MS State (+3, tonight)")
        print("   🏀 Lakers vs Celtics (-5.5, tomorrow)")
        print("   🏈 Chiefs vs Bills (-2.5, this weekend)")

        print("\n" + "="*60)
        print("🎉 Database initialization complete!")
        print("="*60)
        print("\n📋 Quick Start:")
        print("   1. Login as admin@h2h.com / admin123")
        print("   2. View events at /api/v1/sport-events")
        print("   3. Test users can create and take bets")
        print("\n🔗 API Docs: http://localhost:8000/docs")
        print("")


async def main():
    await init_database()
    await seed_data()


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