"""
Migration script to add intent_vector and semantic_examples fields.
Run: python scripts/run_migration_011.py
"""

import asyncio
import os
import sys

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from sqlalchemy import text
from app.core.database import engine


async def run_migration():
    """Execute migration to add new fields."""
    migration_sql = """
    -- Add intent_vector column (JSONB for storing pre-computed embedding vectors)
    ALTER TABLE intent_rules
    ADD COLUMN IF NOT EXISTS intent_vector JSONB;

    -- Add semantic_examples column (JSONB for storing example sentences for dynamic vector computation)
    ALTER TABLE intent_rules
    ADD COLUMN IF NOT EXISTS semantic_examples JSONB;

    -- Add route_trace column to chat_messages table if not exists
    ALTER TABLE chat_messages
    ADD COLUMN IF NOT EXISTS route_trace JSONB;
    """

    async with engine.begin() as conn:
        for statement in migration_sql.strip().split(";"):
            statement = statement.strip()
            if statement and not statement.startswith("--"):
                try:
                    await conn.execute(text(statement))
                    print(f"Executed: {statement[:80]}...")
                except Exception as e:
                    print(f"Error executing: {statement[:80]}...")
                    print(f"  Error: {e}")

    print("\nMigration completed successfully!")


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