"""
AI Studio Proxy Server - Main server module

This module provides the main server functionality that can be imported
and used programmatically.
"""

import os
import asyncio
import logging
from typing import Optional, Dict, Any, List, Set
from asyncio import Queue, Lock, Task

from dotenv import load_dotenv

# Load environment variables
load_dotenv()

from api_utils import create_app

# --- Global State ---
playwright_manager = None
browser_instance = None
page_instance = None
is_playwright_ready = False
is_browser_connected = False
is_page_ready = False
is_initializing = False

# --- Proxy Settings ---
PLAYWRIGHT_PROXY_SETTINGS: Optional[Dict[str, str]] = None

global_model_list_raw_json: Optional[List[Any]] = None
parsed_model_list: List[Dict[str, Any]] = []
model_list_fetch_event = asyncio.Event()

current_ai_studio_model_id: Optional[str] = None
model_switching_lock: Optional[Lock] = None

excluded_model_ids: Set[str] = set()

request_queue: Optional[Queue] = None
processing_lock: Optional[Lock] = None
worker_task: Optional[Task] = None

page_params_cache: Dict[str, Any] = {}
params_cache_lock: Optional[Lock] = None

logger = logging.getLogger("AIStudioProxyServer")
log_ws_manager = None

# Create FastAPI app
app = create_app()


def run_server(
    host: str = "0.0.0.0",
    port: int = 2048,
    log_level: str = "info",
    access_log: bool = False,
    reload: bool = False,
):
    """
    Run the AI Studio Proxy server.
    
    Args:
        host: Host address to bind to (default: "0.0.0.0")
        port: Port number to listen on (default: 2048)
        log_level: Logging level (default: "info")
        access_log: Enable access logging (default: False)
        reload: Enable auto-reload for development (default: False)
    
    Example:
        >>> from aistudio_proxy import run_server
        >>> run_server(port=8080)
    """
    import uvicorn
    
    uvicorn.run(
        "aistudio_proxy.server:app",
        host=host,
        port=port,
        log_level=log_level,
        access_log=access_log,
        reload=reload,
    )


def get_app():
    """
    Get the FastAPI application instance.
    
    Returns:
        FastAPI: The configured FastAPI application
    
    Example:
        >>> from aistudio_proxy import get_app
        >>> app = get_app()
    """
    return app


if __name__ == "__main__":
    port = int(os.environ.get("PORT", 2048))
    run_server(port=port)
