import logging
import os
import sys

sys.path.append(os.getcwd())

from app.core.database import execute_query, init_db
from app.core.config import settings

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


def run_migration():
    migration_file = "migrations/129_sag_pipeline_description.sql"
    logger.info("Applying migration: %s", migration_file)

    try:
        if "@postgres" in settings.DATABASE_URL:
            logger.info("Patching DATABASE_URL for local run")
            settings.DATABASE_URL = settings.DATABASE_URL.replace("@postgres", "@localhost").replace(":5432", ":5433")

        init_db()

        with open(migration_file, "r", encoding="utf-8") as migration:
            sql = migration.read()

        commands = [cmd.strip() for cmd in sql.split(";") if cmd.strip()]

        for command in commands:
            logger.info("Executing migration statement...")
            execute_query(command, ())

        logger.info("✅ Migration 129 applied successfully")
    except Exception as exc:
        logger.error("❌ Migration 129 failed: %s", exc)
        sys.exit(1)


if __name__ == "__main__":
    run_migration()
