"""
Migration script to create shared_sessions table.
Run: python scripts/migrations/create_shared_sessions_table.py
"""

import asyncio
import sys
from pathlib import Path

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

from sqlalchemy import text
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy.orm import sessionmaker
from sqlmodel.ext.asyncio.session import AsyncSession

from app.core.config import get_settings


async def run_migration():
    """Run the migration to create shared_sessions table."""
    settings = get_settings()
    engine = create_async_engine(settings.database_url, echo=True)
    async_session_maker = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)

    migration_sql = """
    CREATE TABLE IF NOT EXISTS shared_sessions (
        id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
        share_token VARCHAR(255) NOT NULL UNIQUE,
        session_id VARCHAR(255) NOT NULL,
        tenant_id VARCHAR(255) NOT NULL,
        title VARCHAR(255),
        description TEXT,
        expires_at TIMESTAMP WITH TIME ZONE NOT NULL,
        is_active BOOLEAN DEFAULT TRUE,
        max_concurrent_users INTEGER DEFAULT 10,
        current_users INTEGER DEFAULT 0,
        created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
        updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
    );

    CREATE INDEX IF NOT EXISTS ix_shared_sessions_share_token ON shared_sessions(share_token);
    CREATE INDEX IF NOT EXISTS ix_shared_sessions_session_id ON shared_sessions(session_id);
    CREATE INDEX IF NOT EXISTS ix_shared_sessions_tenant ON shared_sessions(tenant_id);
    CREATE INDEX IF NOT EXISTS ix_shared_sessions_tenant_session ON shared_sessions(tenant_id, session_id);
    CREATE INDEX IF NOT EXISTS ix_shared_sessions_expires_at ON shared_sessions(expires_at);
    """

    async with async_session_maker() as session:
        for statement in migration_sql.strip().split(';'):
            statement = statement.strip()
            if statement and not statement.startswith('--'):
                try:
                    await session.execute(text(statement))
                    print(f"Executed: {statement[:60]}...")
                except Exception as e:
                    error_str = str(e).lower()
                    if "already exists" in error_str or "duplicate" in error_str:
                        print(f"Skipped (already exists): {statement[:60]}...")
                    else:
                        print(f"Error: {e}")
                        raise
        
        await session.commit()
        print("\nMigration completed successfully!")

    await engine.dispose()


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