#!/usr/bin/env python3
"""
Database initialization script for Sales Model Dashboard

This script creates the PostgreSQL database schema and optionally loads demo data.
"""
from __future__ import annotations

import asyncio
import os
import sys
from pathlib import Path

# Load environment variables
from dotenv import load_dotenv
load_dotenv()

# Add the src directory to Python path
sys.path.insert(0, str(Path(__file__).parent / "src"))

from app.storage.database import init_pool, close_pool, get_connection
from app.dashboard.data import init_demo_data
from app.observability.logging import get_logger

_logger = get_logger("db_init")


async def create_schema():
    """Create database schema from SQL file."""
    schema_file = Path(__file__).parent / "src" / "app" / "storage" / "schema.sql"
    
    if not schema_file.exists():
        _logger.error("Schema file not found", path=str(schema_file))
        return False
    
    with open(schema_file, 'r', encoding='utf-8') as f:
        schema_sql = f.read()
    
    async with get_connection() as conn:
        try:
            # Execute schema in a transaction
            async with conn.transaction():
                await conn.execute(schema_sql)
            
            _logger.info("Database schema created successfully")
            return True
        except Exception as e:
            _logger.error("Failed to create schema", error=str(e))
            return False


async def check_database_connection():
    """Test database connection."""
    try:
        async with get_connection() as conn:
            result = await conn.fetchval("SELECT version()")
            _logger.info("Database connection successful", version=result)
            return True
    except Exception as e:
        _logger.error("Database connection failed", error=str(e))
        return False


async def main():
    """Main initialization function."""
    _logger.info("Starting database initialization")
    
    # Check environment variables
    database_url = os.getenv("DATABASE_URL")
    if not database_url:
        _logger.warning("DATABASE_URL not set, using default PostgreSQL connection")
    else:
        _logger.info("Using database URL from environment")
    
    try:
        # Initialize connection pool
        await init_pool()
        
        # Test connection
        if not await check_database_connection():
            _logger.error("Database connection failed, aborting initialization")
            return
        
        # Create schema
        if not await create_schema():
            _logger.error("Schema creation failed")
            return
        
        # Load demo data if requested
        if "--demo-data" in sys.argv:
            _logger.info("Loading demo data")
            await init_demo_data()
            _logger.info("Demo data loaded successfully")
        
        _logger.info("Database initialization completed successfully")
        
    except Exception as e:
        _logger.error("Database initialization failed", error=str(e))
    finally:
        await close_pool()


if __name__ == "__main__":
    print("🗄️  Sales Model Database Initialization")
    print("=" * 50)
    
    if "--help" in sys.argv or "-h" in sys.argv:
        print("""
Usage: python init_db.py [options]

Options:
  --demo-data    Load demo data for testing
  --help, -h     Show this help message

Environment Variables:
  DATABASE_URL   PostgreSQL connection string
                 (default: postgresql://postgres:postgres@localhost:5432/sales_model)

Examples:
  python init_db.py
  python init_db.py --demo-data
  DATABASE_URL="postgresql://user:pass@host:5432/db" python init_db.py
""")
        sys.exit(0)
    
    asyncio.run(main())