"""
Migration script to add intent_vector and semantic_examples fields to intent_rules table.
[v0.8.0] Hybrid routing - Intent vector fields

Run this script with: python scripts/migrations/011_add_intent_vector_fields.py
"""

import asyncio
import sys
import os

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

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


async def run_migration():
    """Run the migration to add new columns to intent_rules table."""
    
    statements = [
        """
        ALTER TABLE intent_rules 
        ADD COLUMN IF NOT EXISTS intent_vector JSONB;
        """,
        """
        ALTER TABLE intent_rules 
        ADD COLUMN IF NOT EXISTS semantic_examples JSONB;
        """,
        """
        ALTER TABLE chat_messages 
        ADD COLUMN IF NOT EXISTS route_trace JSONB;
        """,
    ]
    
    async with async_session_maker() as session:
        for i, statement in enumerate(statements, 1):
                try:
                    await session.execute(text(statement))
                    print(f"[{i}] Executed successfully")
                except Exception as e:
                    if "already exists" in str(e).lower() or "duplicate" in str(e).lower():
                        print(f"[{i}] Skipped (already exists): {str(e)[:50]}...")
                    else:
                        raise
        
        await session.commit()
        print("\nMigration completed successfully!")


if __name__ == "__main__":
    asyncio.run(run_migration())
else:
    print("Please run this script directly, not imported.")
    sys.exit(1)
