#!/usr/bin/env python3
"""
Database initialization script.
Creates all tables and seeds initial data.

Usage:
    python scripts/init_db.py
"""

import asyncio
import sys
import os

# Add parent directory to path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from app.database import engine, Base

# Import all models to register them with SQLAlchemy (ensures ALL tables are created)
# noqa: F401 - imported for side effects
import app.models  # noqa: F401


async def init_database():
    """Initialize database tables."""
    print("🔧 Initializing database...")
    
    async with engine.begin() as conn:
        # Create all tables
        await conn.run_sync(Base.metadata.create_all)
        # Apply additive migrations (indexes / optional columns)
        from app.db_migrations import apply_migrations
        await apply_migrations(conn)
    
    print("✅ Database tables created successfully!")
    print("")
    print("Tables created:")
    for table in Base.metadata.tables.keys():
        print(f"  - {table}")


async def seed_tld_data():
    """Seed initial TLD data."""
    from sqlalchemy.ext.asyncio import AsyncSession
    from sqlalchemy.orm import sessionmaker
    from app.models.tld_price import TLDInfo
    from sqlalchemy import select
    
    AsyncSessionLocal = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
    
    # Basic TLD data
    tld_data = [
        {"tld": "com", "type": "generic", "description": "Commercial", "popularity_rank": 1},
        {"tld": "net", "type": "generic", "description": "Network", "popularity_rank": 2},
        {"tld": "org", "type": "generic", "description": "Organization", "popularity_rank": 3},
        {"tld": "io", "type": "country", "description": "Tech startups", "popularity_rank": 4},
        {"tld": "co", "type": "country", "description": "Company/Colombia", "popularity_rank": 5},
        {"tld": "ai", "type": "country", "description": "AI/Anguilla", "popularity_rank": 6},
        {"tld": "dev", "type": "generic", "description": "Developers", "popularity_rank": 7},
        {"tld": "app", "type": "generic", "description": "Applications", "popularity_rank": 8},
        {"tld": "xyz", "type": "generic", "description": "Generation XYZ", "popularity_rank": 9},
        {"tld": "me", "type": "country", "description": "Personal/Montenegro", "popularity_rank": 10},
        {"tld": "ch", "type": "country", "description": "Switzerland", "popularity_rank": 11},
        {"tld": "de", "type": "country", "description": "Germany", "popularity_rank": 12},
        {"tld": "uk", "type": "country", "description": "United Kingdom", "popularity_rank": 13},
        {"tld": "fr", "type": "country", "description": "France", "popularity_rank": 14},
        {"tld": "nl", "type": "country", "description": "Netherlands", "popularity_rank": 15},
    ]
    
    async with AsyncSessionLocal() as session:
        for data in tld_data:
            # Check if exists
            result = await session.execute(
                select(TLDInfo).where(TLDInfo.tld == data["tld"])
            )
            existing = result.scalar_one_or_none()
            
            if not existing:
                tld_info = TLDInfo(**data)
                session.add(tld_info)
                print(f"  Added: .{data['tld']}")
        
        await session.commit()
    
    print("✅ TLD data seeded!")


async def main():
    """Run all initialization steps."""
    print("=" * 50)
    print("POUNCE Database Initialization")
    print("=" * 50)
    print("")
    
    await init_database()
    print("")
    
    print("🌱 Seeding initial data...")
    await seed_tld_data()
    print("")
    
    print("=" * 50)
    print("✅ Database initialization complete!")
    print("=" * 50)


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

