#!/usr/bin/env python3
"""
Script to drop and recreate Milvus collection with new unified schema.
"""

import os
import asyncio

# Override settings before importing (for local execution)
os.environ['MILVUS_HOST'] = 'localhost'
os.environ['MILVUS_PORT'] = '19530'

from pymilvus import connections, utility
from src.core.config import settings
from src.knowledge.vector_store import VectorStore


async def recreate_collection():
    """Drop existing collection and create new one with unified schema."""

    print("=" * 70)
    print("Recreating Milvus Collection with Unified Schema")
    print("=" * 70)

    # Connect to Milvus (use localhost for local execution)
    milvus_host = "localhost"
    milvus_port = 19530
    print(f"\n1️⃣  Connecting to Milvus at {milvus_host}:{milvus_port}...")
    connections.connect(
        alias="default",
        host=milvus_host,
        port=milvus_port,
    )
    print("✅ Connected to Milvus")

    # Check if collection exists
    collection_name = settings.milvus_collection
    print(f"\n2️⃣  Checking for existing collection '{collection_name}'...")

    if utility.has_collection(collection_name):
        print(f"⚠️  Collection '{collection_name}' exists")
        print(f"🗑️  Dropping collection...")
        utility.drop_collection(collection_name)
        print(f"✅ Collection dropped")
    else:
        print(f"ℹ️  Collection '{collection_name}' does not exist")

    # Disconnect
    connections.disconnect("default")
    print(f"\n3️⃣  Creating new collection with unified schema...")

    # Create new collection with unified schema
    vector_store = VectorStore()
    await vector_store.create_collection()

    print(f"✅ New collection created with unified schema:")
    print(f"   - vector (FLOAT_VECTOR, dim=3072)")
    print(f"   - record_id (VARCHAR)")
    print(f"   - document_id (VARCHAR)")
    print(f"   - filename (VARCHAR)")
    print(f"   - document_type (VARCHAR)")
    print(f"   - text_content (VARCHAR)")
    print(f"   - metadata (JSON)")
    print(f"   - domain_category (VARCHAR) [DOMAIN-AWARE RAG]")
    print(f"   - domain_terms (ARRAY<VARCHAR>) [DOMAIN-AWARE RAG]")
    print(f"   - tags (ARRAY<VARCHAR>) [SEMANTIC TAGGING]")

    print("\n" + "=" * 70)
    print("Collection Recreation Complete!")
    print("=" * 70)
    print("\nReady to ingest documents with the new schema.")


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