#!/usr/bin/env python3
"""
Quick Test - Verify Cheshire Cat is working with Miku personality
"""

import requests
import time

CAT_URL = "http://localhost:1865"

def test_query(query, timeout=60):
    """Test a single query"""
    print(f"\n❓ Query: {query}")
    start = time.time()
    
    try:
        response = requests.post(
            f"{CAT_URL}/message",
            json={"text": query},
            headers={"Content-Type": "application/json"},
            timeout=timeout
        )
        
        elapsed = (time.time() - start) * 1000
        
        if response.status_code == 200:
            data = response.json()
            content = data.get("content", "")
            
            # Check if it's a tool call (shouldn't be)
            if content.startswith('{"name":'):
                print(f"   ❌ Got tool call instead of text ({elapsed:.0f}ms)")
                print(f"   Content: {content[:100]}")
                return False
            
            print(f"   ✅ Success ({elapsed:.0f}ms)")
            print(f"   Response: {content}")
            return True
        else:
            print(f"   ❌ HTTP {response.status_code} ({elapsed:.0f}ms)")
            return False
            
    except requests.exceptions.Timeout:
        print(f"   ⏱️  Timeout after {timeout}s (model might be loading)")
        return False
    except Exception as e:
        print(f"   ❌ Error: {e}")
        return False

def main():
    print("=" * 70)
    print("🐱 Cheshire Cat Quick Test - Miku Personality")
    print("=" * 70)
    
    # Check if Cat is running
    try:
        response = requests.get(f"{CAT_URL}/", timeout=5)
        print(f"\n✅ Cat is running (v{response.json().get('version', 'unknown')})")
    except:
        print("\n❌ Cat is not responding at http://localhost:1865")
        print("   Make sure containers are running:")
        print("   docker-compose -f docker-compose.test.yml up -d")
        return
    
    # Check plugin status
    try:
        response = requests.get(f"{CAT_URL}/plugins/", timeout=5)
        plugins = response.json()
        miku_plugin = None
        for plugin in plugins.get('installed', []):
            if plugin['id'] == 'miku_personality':
                miku_plugin = plugin
                break
        
        if miku_plugin:
            if miku_plugin['active']:
                print(f"✅ Miku personality plugin is ACTIVE")
            else:
                print(f"⚠️  Miku personality plugin is INACTIVE")
                print("   Activating...")
                requests.put(f"{CAT_URL}/plugins/toggle/miku_personality")
                print("   ✅ Activated!")
        else:
            print("❌ Miku personality plugin not found")
    except Exception as e:
        print(f"⚠️  Could not check plugin status: {e}")
    
    # Test queries
    print("\n" + "=" * 70)
    print("Running test queries...")
    print("=" * 70)
    
    queries = [
        "Hi! What's your name?",
        "What is your favorite food?",
        "Who are your friends?",
    ]
    
    success_count = 0
    
    # First query might be slow (model loading)
    print("\n⏳ First query may take 30-45s (loading darkidol model)...")
    
    for query in queries:
        if test_query(query):
            success_count += 1
        time.sleep(2)
    
    # Results
    print("\n" + "=" * 70)
    print("📊 RESULTS")
    print("=" * 70)
    print(f"Successful: {success_count}/{len(queries)}")
    
    if success_count == len(queries):
        print("\n✅ ALL TESTS PASSED!")
        print("\nNext steps:")
        print("  - Run full benchmarks: python3 benchmark_cat.py")
        print("  - Compare systems: python3 compare_systems.py")
        print("  - Use admin panel: http://localhost:1865/admin")
    elif success_count > 0:
        print("\n⚠️  SOME TESTS FAILED")
        print("   Check logs: docker logs miku_cheshire_cat_test")
    else:
        print("\n❌ ALL TESTS FAILED")
        print("   Troubleshooting:")
        print("   1. Check logs: docker logs miku_cheshire_cat_test")
        print("   2. Check llama-swap: docker logs llama-swap-amd")
        print("   3. Verify network: docker inspect miku_cheshire_cat_test")

if __name__ == "__main__":
    main()
