#!/usr/bin/env python3
"""
VSS Connection Test Script
Verifies connectivity to all required services.
"""

import asyncio
import sys
sys.path.insert(0, '..')

from config.settings import get_settings
from storage.clickhouse_client import get_clickhouse
from inference.llm_client import get_llm
from inference.vlm_client import get_vlm


def test_clickhouse():
    """Test ClickHouse connection."""
    print("\n=== ClickHouse ===")
    settings = get_settings()
    print(f"Host: {settings.clickhouse.host}:{settings.clickhouse.port}")
    print(f"Database: {settings.clickhouse.database}")
    print(f"Table: {settings.clickhouse.table}")
    
    try:
        ch = get_clickhouse()
        if ch.test_connection():
            print("✓ Connection OK")
            
            # Test query
            apps = ch.get_applications()
            print(f"✓ Applications: {len(apps)}")
            for app in apps:
                print(f"  - {app['applicationName']}")
            
            cats = ch.get_categories()
            print(f"✓ Categories: {', '.join(cats)}")
            
            tr = ch.get_time_range()
            print(f"✓ Data range: {tr.get('earliest')} to {tr.get('latest')}")
            print(f"✓ Total rows: {tr.get('total')}")
            
            return True
        else:
            print("✗ Connection failed")
            return False
    except Exception as e:
        print(f"✗ Error: {e}")
        return False


async def test_llm():
    """Test LLM (Ollama) connection."""
    print("\n=== LLM (Ollama) ===")
    settings = get_settings()
    print(f"Endpoint: {settings.llm.endpoint}")
    print(f"Model: {settings.llm.model_name}")
    
    try:
        llm = get_llm()
        if await llm.health_check():
            print("✓ Service available")
            
            # Test generation
            response = await llm.generate("Say 'VSS LLM OK' in 3 words.", max_tokens=10)
            print(f"✓ Test response: {response}")
            return True
        else:
            print("✗ Service unavailable")
            return False
    except Exception as e:
        print(f"✗ Error: {e}")
        return False


async def test_vlm():
    """Test VLM (vLLM) connection."""
    print("\n=== VLM (Cosmos) ===")
    settings = get_settings()
    print(f"Endpoint: {settings.vlm.endpoint}")
    print(f"Model: {settings.vlm.model_name}")
    
    try:
        vlm = get_vlm()
        if await vlm.health_check():
            print("✓ Service available")
            return True
        else:
            print("✗ Service unavailable (this is OK if VLM not started)")
            return False
    except Exception as e:
        print(f"✗ Error: {e}")
        return False


async def main():
    print("=" * 50)
    print("VSS Connection Test")
    print("=" * 50)
    
    results = {}
    
    results["clickhouse"] = test_clickhouse()
    results["llm"] = await test_llm()
    results["vlm"] = await test_vlm()
    
    print("\n" + "=" * 50)
    print("Summary")
    print("=" * 50)
    
    for name, ok in results.items():
        status = "✓ OK" if ok else "✗ FAIL"
        print(f"  {name}: {status}")
    
    all_ok = all(results.values())
    critical_ok = results["clickhouse"] and results["llm"]
    
    print()
    if all_ok:
        print("All services ready!")
    elif critical_ok:
        print("Core services ready (VLM optional for SQL queries)")
    else:
        print("Some services unavailable - check configuration")
    
    return 0 if critical_ok else 1


if __name__ == "__main__":
    exit(asyncio.run(main()))