import logging
import os
import sys

# Ensure we can import app modules
sys.path.append("/app")

from app.core.database import execute_query, init_db

# Setup logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

SQL_MIGRATION = """
CREATE TABLE IF NOT EXISTS sag_solutions (
    id SERIAL PRIMARY KEY,
    sag_id INTEGER NOT NULL REFERENCES sag_sager(id) ON DELETE CASCADE,
    title VARCHAR(255) NOT NULL,
    description TEXT,
    solution_type VARCHAR(50), 
    result VARCHAR(50),        
    created_by_user_id INTEGER, 
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    CONSTRAINT uq_sag_solutions_sag_id UNIQUE (sag_id)
);

ALTER TABLE tmodule_times ADD COLUMN IF NOT EXISTS solution_id INTEGER REFERENCES sag_solutions(id) ON DELETE SET NULL;

ALTER TABLE tmodule_times ADD COLUMN IF NOT EXISTS sag_id INTEGER REFERENCES sag_sager(id) ON DELETE SET NULL;

ALTER TABLE tmodule_times ALTER COLUMN vtiger_id DROP NOT NULL;

ALTER TABLE tmodule_times ALTER COLUMN case_id DROP NOT NULL;

CREATE INDEX IF NOT EXISTS idx_sag_solutions_sag_id ON sag_solutions(sag_id);

CREATE INDEX IF NOT EXISTS idx_tmodule_times_solution_id ON tmodule_times(solution_id);

CREATE INDEX IF NOT EXISTS idx_tmodule_times_sag_id ON tmodule_times(sag_id);
"""

def run_migration():
    logger.info("Initializing DB connection...")
    try:
        init_db()
    except Exception as e:
        logger.error(f"Failed to init db: {e}")
        return

    logger.info("Applying migration 085...")
    
    commands = [cmd.strip() for cmd in SQL_MIGRATION.split(";") if cmd.strip()]
    
    for cmd in commands:
        # Skip empty lines or pure comments
        if not cmd or cmd.startswith("--"):
            continue
            
        logger.info(f"Executing: {cmd[:50]}...")
        try:
            execute_query(cmd, ())
        except Exception as e:
            logger.warning(f"Error executing command: {e}")
            
    logger.info("✅ Migration applied successfully")

if __name__ == "__main__":
    run_migration()
