#!/usr/bin/env python3
"""Script pour initialiser la base de données et créer le compte admin"""

import asyncio
import os
import bcrypt
from dotenv import load_dotenv
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
from sqlalchemy import text

load_dotenv()

DATABASE_URL = os.environ.get('DATABASE_URL')
ADMIN_EMAIL = os.environ.get('ADMIN_EMAIL', 'admin@apora.net')
ADMIN_PASSWORD = os.environ.get('ADMIN_PASSWORD', 'OporaVie2026!')

def hash_password(password: str) -> str:
    return bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')

async def init_database():
    print("Connexion a la base de donnees...")
    engine = create_async_engine(DATABASE_URL, echo=False)
    
    async with engine.begin() as conn:
        print("Creation des tables...")
        
        # Users table
        await conn.execute(text("""
            CREATE TABLE IF NOT EXISTS users (
                id VARCHAR(36) PRIMARY KEY,
                email VARCHAR(255) UNIQUE NOT NULL,
                first_name VARCHAR(255) NOT NULL,
                last_name VARCHAR(255) NOT NULL,
                phone VARCHAR(50),
                password VARCHAR(255) NOT NULL,
                role VARCHAR(50) NOT NULL DEFAULT 'client',
                created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
                google_calendar_connected BOOLEAN DEFAULT FALSE,
                google_tokens JSONB
            )
        """))
        print("  - Table 'users' creee")
        
        # Practitioners table
        await conn.execute(text("""
            CREATE TABLE IF NOT EXISTS practitioners (
                id VARCHAR(36) PRIMARY KEY,
                user_id VARCHAR(36) REFERENCES users(id) ON DELETE CASCADE,
                specialty VARCHAR(100) NOT NULL,
                bio TEXT,
                photo_url VARCHAR(500),
                country VARCHAR(10) DEFAULT 'FR',
                region VARCHAR(100),
                department VARCHAR(100),
                address VARCHAR(255),
                city VARCHAR(100),
                postal_code VARCHAR(20),
                consultation_types JSONB DEFAULT '["cabinet"]',
                price DECIMAL(10, 2),
                consultation_duration INTEGER DEFAULT 60,
                is_verified BOOLEAN DEFAULT FALSE,
                years_experience INTEGER,
                diplomas JSONB,
                detailed_description TEXT,
                languages JSONB
            )
        """))
        print("  - Table 'practitioners' creee")
        
        # Time slots table
        await conn.execute(text("""
            CREATE TABLE IF NOT EXISTS time_slots (
                id VARCHAR(36) PRIMARY KEY,
                practitioner_id VARCHAR(36) REFERENCES practitioners(id) ON DELETE CASCADE,
                day_of_week INTEGER NOT NULL,
                start_time VARCHAR(10) NOT NULL,
                end_time VARCHAR(10) NOT NULL
            )
        """))
        print("  - Table 'time_slots' creee")
        
        # Appointments table
        await conn.execute(text("""
            CREATE TABLE IF NOT EXISTS appointments (
                id VARCHAR(36) PRIMARY KEY,
                client_id VARCHAR(36) REFERENCES users(id) ON DELETE CASCADE,
                practitioner_id VARCHAR(36) REFERENCES practitioners(id) ON DELETE CASCADE,
                date VARCHAR(20) NOT NULL,
                start_time VARCHAR(10) NOT NULL,
                end_time VARCHAR(10) NOT NULL,
                consultation_type VARCHAR(50) NOT NULL,
                status VARCHAR(50) DEFAULT 'pending',
                notes TEXT,
                video_room_url VARCHAR(500),
                google_event_id VARCHAR(255),
                paid BOOLEAN DEFAULT FALSE,
                created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
            )
        """))
        print("  - Table 'appointments' creee")
        
        # Payment transactions table
        await conn.execute(text("""
            CREATE TABLE IF NOT EXISTS payment_transactions (
                id VARCHAR(36) PRIMARY KEY,
                session_id VARCHAR(255),
                appointment_id VARCHAR(36) REFERENCES appointments(id) ON DELETE SET NULL,
                client_id VARCHAR(36) REFERENCES users(id) ON DELETE SET NULL,
                amount DECIMAL(10, 2),
                currency VARCHAR(10) DEFAULT 'eur',
                status VARCHAR(50) DEFAULT 'pending',
                payment_status VARCHAR(50) DEFAULT 'initiated',
                created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
            )
        """))
        print("  - Table 'payment_transactions' creee")
        
        # Admin settings table
        await conn.execute(text("""
            CREATE TABLE IF NOT EXISTS admin_settings (
                key VARCHAR(100) PRIMARY KEY,
                value TEXT,
                updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
            )
        """))
        print("  - Table 'admin_settings' creee")
        
        # SMS reminders log table
        await conn.execute(text("""
            CREATE TABLE IF NOT EXISTS sms_reminders (
                id VARCHAR(36) PRIMARY KEY,
                appointment_id VARCHAR(36) REFERENCES appointments(id) ON DELETE CASCADE,
                phone_number VARCHAR(50),
                message TEXT,
                status VARCHAR(50) DEFAULT 'pending',
                sent_at TIMESTAMP WITH TIME ZONE,
                error_message TEXT,
                created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
            )
        """))
        print("  - Table 'sms_reminders' creee")
        
        # Create indexes
        await conn.execute(text("CREATE INDEX IF NOT EXISTS idx_users_email ON users(email)"))
        await conn.execute(text("CREATE INDEX IF NOT EXISTS idx_practitioners_user_id ON practitioners(user_id)"))
        await conn.execute(text("CREATE INDEX IF NOT EXISTS idx_practitioners_specialty ON practitioners(specialty)"))
        await conn.execute(text("CREATE INDEX IF NOT EXISTS idx_appointments_client_id ON appointments(client_id)"))
        await conn.execute(text("CREATE INDEX IF NOT EXISTS idx_appointments_practitioner_id ON appointments(practitioner_id)"))
        await conn.execute(text("CREATE INDEX IF NOT EXISTS idx_appointments_date ON appointments(date)"))
        print("  - Index crees")
        
        # Initialize default settings
        await conn.execute(text("""
            INSERT INTO admin_settings (key, value, updated_at) 
            VALUES ('sms_reminders_enabled', 'false', NOW())
            ON CONFLICT (key) DO NOTHING
        """))
        print("  - Parametres par defaut initialises")
        
        print("\nToutes les tables ont ete creees avec succes!")
    
    # Maintenant creer l'admin
    async_session_maker = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
    
    async with async_session_maker() as session:
        # Verifier si l'admin existe deja
        result = await session.execute(
            text("SELECT * FROM users WHERE email = :email"),
            {"email": ADMIN_EMAIL}
        )
        existing = result.fetchone()
        
        if existing:
            print(f"\nLe compte admin {ADMIN_EMAIL} existe deja!")
        else:
            # Creer le compte admin
            import uuid
            admin_id = str(uuid.uuid4())
            hashed = hash_password(ADMIN_PASSWORD)
            await session.execute(
                text("""
                    INSERT INTO users (id, email, password, role, first_name, last_name, created_at)
                    VALUES (:id, :email, :password, 'admin', 'Admin', 'Opora Vie', NOW())
                """),
                {"id": admin_id, "email": ADMIN_EMAIL, "password": hashed}
            )
            await session.commit()
            print(f"\nCompte admin cree avec succes!")
            print(f"  Email: {ADMIN_EMAIL}")
            print(f"  Mot de passe: {ADMIN_PASSWORD}")
    
    await engine.dispose()
    print("\nInitialisation terminee!")

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