#!/usr/bin/env python3
"""
Verification script to test burt-logger installation and basic functionality.

Run this after installing the package to verify everything works correctly.
"""

import sys
import time
from typing import Tuple


def test_import() -> Tuple[bool, str]:
    """Test that the package can be imported."""
    try:
        from burt_logger import LLMLogger
        return True, "✓ Package imported successfully"
    except ImportError as e:
        return False, f"✗ Failed to import package: {e}"


def test_initialization() -> Tuple[bool, str]:
    """Test that logger can be initialized."""
    try:
        from burt_logger import LLMLogger
        
        logger = LLMLogger(
            endpoint="https://test.example.com/logs",
            api_key="test-key",
            batch_size=10,
            flush_interval=5.0,
        )
        logger.shutdown(timeout=1.0)
        return True, "✓ Logger initialized successfully"
    except Exception as e:
        return False, f"✗ Failed to initialize logger: {e}"


def test_logging() -> Tuple[bool, str]:
    """Test basic logging functionality."""
    try:
        from burt_logger import LLMLogger
        
        logger = LLMLogger(
            endpoint="https://test.example.com/logs",
            api_key="test-key",
            batch_size=100,  # Large batch to prevent sending
        )
        
        # Test logging
        success = logger.log(
            request={"model": "test", "prompt": "test"},
            response={"completion": "test"},
        )
        
        if not success:
            return False, "✗ Failed to queue log entry"
        
        # Test with metadata
        success = logger.log(
            request={"model": "test"},
            response={"result": "test"},
            metadata={"user": "test"},
        )
        
        if not success:
            return False, "✗ Failed to queue log with metadata"
        
        # Check stats
        stats = logger.get_stats()
        if stats["logs_queued"] != 2:
            return False, f"✗ Expected 2 logs queued, got {stats['logs_queued']}"
        
        logger.shutdown(timeout=1.0)
        return True, "✓ Logging functionality works correctly"
    except Exception as e:
        return False, f"✗ Logging test failed: {e}"


def test_context_manager() -> Tuple[bool, str]:
    """Test context manager functionality."""
    try:
        from burt_logger import LLMLogger
        
        with LLMLogger(endpoint="https://test.example.com/logs", api_key="test") as logger:
            logger.log(request={"test": 1}, response={"result": 1})
        
        return True, "✓ Context manager works correctly"
    except Exception as e:
        return False, f"✗ Context manager test failed: {e}"


def test_thread_safety() -> Tuple[bool, str]:
    """Test basic thread safety."""
    try:
        import threading
        from burt_logger import LLMLogger
        
        logger = LLMLogger(
            endpoint="https://test.example.com/logs",
            api_key="test",
            max_queue_size=1000,
        )
        
        def worker(thread_id):
            for i in range(10):
                logger.log(
                    request={"thread": thread_id, "index": i},
                    response={"result": i},
                )
        
        threads = []
        for i in range(5):
            t = threading.Thread(target=worker, args=(i,))
            threads.append(t)
            t.start()
        
        for t in threads:
            t.join()
        
        stats = logger.get_stats()
        if stats["logs_queued"] != 50:
            return False, f"✗ Expected 50 logs from threads, got {stats['logs_queued']}"
        
        logger.shutdown(timeout=2.0)
        return True, "✓ Thread safety test passed"
    except Exception as e:
        return False, f"✗ Thread safety test failed: {e}"


def test_dependencies() -> Tuple[bool, str]:
    """Test that required dependencies are available."""
    try:
        import requests
        return True, "✓ Required dependencies (requests) installed"
    except ImportError:
        return False, "✗ Missing required dependency: requests (pip install requests)"


def main():
    """Run all verification tests."""
    print("=" * 60)
    print("Burt Logger - Installation Verification")
    print("=" * 60)
    print()
    
    tests = [
        ("Dependency Check", test_dependencies),
        ("Package Import", test_import),
        ("Logger Initialization", test_initialization),
        ("Basic Logging", test_logging),
        ("Context Manager", test_context_manager),
        ("Thread Safety", test_thread_safety),
    ]
    
    results = []
    
    for test_name, test_func in tests:
        print(f"Running: {test_name}...", end=" ")
        sys.stdout.flush()
        
        try:
            success, message = test_func()
            results.append((test_name, success))
            print(message)
        except Exception as e:
            results.append((test_name, False))
            print(f"✗ Unexpected error: {e}")
        
        time.sleep(0.1)
    
    print()
    print("=" * 60)
    print("Summary")
    print("=" * 60)
    
    passed = sum(1 for _, success in results if success)
    total = len(results)
    
    print(f"Passed: {passed}/{total}")
    print()
    
    if passed == total:
        print("✓ All tests passed! Burt Logger is ready to use.")
        print()
        print("Next steps:")
        print("  1. Read QUICKSTART.md for usage examples")
        print("  2. Check examples/ directory for integration samples")
        print("  3. Run 'python examples/simple_example.py' for a demo")
        return 0
    else:
        print("✗ Some tests failed. Please check the errors above.")
        print()
        print("Common fixes:")
        print("  - Run: pip install requests")
        print("  - Reinstall: pip install --force-reinstall burt-logger")
        print("  - Check Python version: python --version (need >= 3.7)")
        return 1


if __name__ == "__main__":
    sys.exit(main())

