import os
from typing import Optional, Any, Dict
import openai
from openai import AsyncOpenAI
from agents import Agent, Model, ModelProvider, OpenAIChatCompletionsModel, RunConfig, Runner, set_tracing_disabled


class TestModel:
    """Test model class for testing with openai-agent, implemented as a singleton."""
    
    _instance = None
    
    def __new__(cls):
        if cls._instance is None:
            cls._instance = super(TestModel, cls).__new__(cls)
            cls._instance._initialize()
        return cls._instance
    
    def _initialize(self):
        """Initialize the test model with OpenAI configuration."""
        # Get API key from environment variable
        api_key = os.environ.get("OPENAI_API_KEY")
        
        if not api_key:
            raise ValueError("OPENAI_API_KEY environment variable is required")
        
        # Use DeepSeek as the model
        self.model = "deepseek-chat"
        self.base_url = "https://api.deepseek.com/v1"
        
        # Create custom OpenAI client for DeepSeek
        self.client = AsyncOpenAI(base_url=self.base_url, api_key=api_key)
        
        # Disable tracing to avoid needing OpenAI API key for tracing
        set_tracing_disabled(disabled=True)
        
        # Create custom model provider
        class CustomModelProvider(ModelProvider):
            def __init__(self, model, client):
                self.model = model
                self.client = client
            
            def get_model(self, model_name: str | None) -> Model:
                return OpenAIChatCompletionsModel(model=model_name or self.model, openai_client=self.client)
        
        self.model_provider = CustomModelProvider(self.model, self.client)
    
    def get_agent(self, tools: list = None):
        """Get an openai-agent instance for testing.
        
        Args:
            tools: List of tools to include in the agent
            
        Returns:
            Agent instance
        """
        return Agent(
            name="test-agent",
            instructions="You are a helpful assistant that can use SQLite tools to execute SQL queries, create tables, and manage database operations.",
            model=self.model,
            tools=tools or []
        )
    
    def run_agent(self, agent, task):
        """Run the agent with the custom model provider.
        
        Args:
            agent: Agent instance to run
            task: Task to execute
            
        Returns:
            Run result
        """
        import asyncio
        
        async def run_task():
            result = await Runner.run(
                agent,
                task,
                run_config=RunConfig(model_provider=self.model_provider),
            )
            return result
        
        return asyncio.run(run_task())


def get_test_model() -> TestModel:
    """Get the singleton test model instance."""
    return TestModel()
