"""FastGPT client dependency injection."""
from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastgpt_client import AsyncChatClient
from .config import Config

# Global client instance
_fastgpt_client: AsyncChatClient | None = None


@asynccontextmanager
async def lifespan(app: FastAPI):
    """Manage FastGPT client lifecycle."""
    global _fastgpt_client
    Config.validate()
    
    # Initialize client
    _fastgpt_client = AsyncChatClient(
        api_key=Config.FASTGPT_API_KEY,
        base_url=Config.FASTGPT_BASE_URL,
        timeout=60.0,
        max_retries=3,
        retry_delay=1.0,
        enable_logging=Config.DEBUG,
    )
    await _fastgpt_client.__aenter__()
    
    yield
    
    # Cleanup
    if _fastgpt_client:
        await _fastgpt_client.__aexit__(None, None, None)


def get_fastgpt_client() -> AsyncChatClient:
    """Get the FastGPT client instance."""
    if _fastgpt_client is None:
        raise RuntimeError("FastGPT client not initialized")
    return _fastgpt_client
