"""Simple test script to verify the library works."""
import os
import sys
from dotenv import load_dotenv

# Add the src directory to path for testing (to import tamu_chat)
# Since tamu_chat is now in src/tamu_chat/, we need to add src/ to the path
parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
src_dir = os.path.join(parent_dir, 'src')
if src_dir not in sys.path:
    sys.path.insert(0, src_dir)

# Load .env file from parent directory
load_dotenv(dotenv_path=os.path.join(parent_dir, '.env'))

from tamu_chat import TAMUChatClient, ChatCompletionResponse

def test_imports():
    """Test that all imports work correctly."""
    print("Testing imports...")
    try:
        from tamu_chat import (
            TAMUChatClient,
            ChatCompletionResponse,
            TAMUChatError,
            APIError,
            AuthenticationError,
            InvalidModelError,
            NoResponseError,
            NetworkError,
            JSONDecodeError,
            get_api_key,
            get_base_url,
        )
        print("[OK] All imports successful")
        return True
    except ImportError as e:
        print(f"[FAIL] Import failed: {e}")
        return False

def test_client_initialization():
    """Test client initialization."""
    print("\nTesting client initialization...")
    try:
        # Test with explicit API key
        client = TAMUChatClient(api_key="sk-test")
        print("[OK] Client initialized with explicit API key")
        print(f"  Base URL: {client.base_url}")
        
        # Test initialization from environment/.env (if available)
        api_key_from_env = os.getenv('TAMU_CHAT_API_KEY')
        if api_key_from_env:
            client_env = TAMUChatClient()  # Should use API key from .env
            print("[OK] Client initialized from .env file")
            print(f"  Base URL: {client_env.base_url}")
        else:
            print("[INFO] No API key in environment/.env - skipping env test")
        
        return True
    except Exception as e:
        print(f"[FAIL] Client initialization failed: {e}")
        return False

def test_response_model():
    """Test response model."""
    print("\nTesting response model...")
    try:
        # Create a mock response
        mock_response = {
            "id": "test-id",
            "model": "test-model",
            "choices": [{
                "message": {
                    "content": "Test response",
                    "role": "assistant"
                }
            }]
        }
        
        response = ChatCompletionResponse.from_api_response(mock_response)
        assert response.text == "Test response"
        assert response.model == "test-model"
        assert response.id == "test-id"
        print("[OK] Response model works correctly")
        return True
    except Exception as e:
        print(f"[FAIL] Response model test failed: {e}")
        return False

if __name__ == "__main__":
    print("=" * 60)
    print("TAMU Chat Library - Structure Test")
    print("=" * 60)
    
    results = []
    results.append(test_imports())
    results.append(test_client_initialization())
    results.append(test_response_model())
    
    print("\n" + "=" * 60)
    if all(results):
        print("[OK] All structure tests passed!")
        
        # Test actual API call if API key is available
        api_key = os.getenv('TAMU_CHAT_API_KEY')
        if api_key:
            print("\nTesting actual API call...")
            try:
                client = TAMUChatClient(api_key=api_key)
                result = client.chat_completion("Say hello in one word")
                print(f"[OK] API call successful!")
                print(f"  Response: {result.text}")
                print(f"  Model: {result.model}")
                
                # Test list_models
                print("\nTesting list_models()...")
                models = client.list_models()
                model_count = len(models) if isinstance(models, list) else 0
                print(f"[OK] Retrieved {model_count} model(s)")
                if models and isinstance(models, list) and len(models) > 0:
                    first_model = models[0]
                    if isinstance(first_model, dict):
                        model_id = first_model.get('id', 'N/A')
                        model_name = first_model.get('name', 'N/A')
                        print(f"  First model: {model_id} - {model_name}")
                    else:
                        print(f"  First model: {first_model}")
            except Exception as e:
                print(f"[FAIL] API test failed: {e}")
        else:
            print("\nNote: To test actual API calls, set TAMU_CHAT_API_KEY in .env file")
            print("Example:")
            print("  client = TAMUChatClient(api_key='sk-your-key')")
            print("  result = client.chat_completion('Hello')")
    else:
        print("[FAIL] Some tests failed")
    print("=" * 60)

