import logging
import os
import sys

# Add project root to path
sys.path.append(os.getcwd())

from app.core.database import execute_query

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

def run_migration():
    migration_file = "migrations/085_sag_solutions.sql"
    logger.info(f"Applying migration: {migration_file}")
    
    try:
        with open(migration_file, "r") as f:
            sql = f.read()
            
        # Split by command (simple split by semicolon)
        # Note: This is a fragile split, but works for simple migrations without function bodies containing semicolons
        commands = [cmd.strip() for cmd in sql.split(";") if cmd.strip()]
        
        for cmd in commands:
            logger.info(f"Executing: {cmd[:50]}...")
            execute_query(cmd, ())
            
        logger.info("✅ Migration applied successfully")
    except Exception as e:
        logger.error(f"❌ Migration failed: {e}")
        sys.exit(1)

if __name__ == "__main__":
    run_migration()
