import os

import uvicorn
import logging
from pathlib import Path

# Configure logging. Default to openarc.log in project root, but can be overridden with OPENARC_LOG_FILE env var.
# Setting this to /dev/null effectively disables file logging if desired.
default_log_file = Path(__file__).parent.parent.parent.parent / "openarc.log"
log_file = Path(os.getenv("OPENARC_LOG_FILE", default_log_file))

# Create a custom logging configuration for uvicorn
LOG_CONFIG = {
    "version": 1,
    "disable_existing_loggers": False,
    "formatters": {
        "default": {
            "format": "%(asctime)s - %(levelname)s - %(message)s",
        },
        "access": {
            "format": "%(asctime)s - %(levelname)s - %(message)s",
        },
    },
    "handlers": {
        "default": {
            "formatter": "default",
            "class": "logging.StreamHandler",
            "stream": "ext://sys.stderr",
        },
        "file": {
            "formatter": "default",
            "class": "logging.FileHandler",
            "filename": str(log_file),
        },
        "access": {
            "formatter": "access",
            "class": "logging.StreamHandler",
            "stream": "ext://sys.stdout",
        },
        "access_file": {
            "formatter": "access",
            "class": "logging.FileHandler",
            "filename": str(log_file),
        },
    },
    "loggers": {
        "uvicorn": {
            "handlers": ["default", "file"],
            "level": "INFO",
            "propagate": False,
        },
        "uvicorn.error": {
            "level": "INFO",
            "handlers": ["default", "file"],
            "propagate": False,
        },
        "uvicorn.access": {
            "handlers": ["access", "access_file"],
            "level": "WARNING",  # Disabled - using custom RequestLoggingMiddleware instead
            "propagate": False,
        },
    },
    "root": {
        "level": "INFO",
        "handlers": ["default", "file"],
    },
}

# Configure root logger
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.StreamHandler(),
        logging.FileHandler(log_file)
    ]
)

logger = logging.getLogger("OpenArc")

def start_server(host: str = "0.0.0.0", port: int = 8001, reload: bool = False):
    """
    Launches the OpenArc API server
    
    Args:
        host: Host to bind the server to
        port: Port to bind the server to
    """
    logger.info(f"Launching  {host}:{port}")
    logger.info("--------------------------------")
    logger.info("OpenArc endpoints:")
    logger.info("  - POST   /openarc/load           Load a model")
    logger.info("  - POST   /openarc/unload         Unload a model")
    logger.info("  - GET    /openarc/status         Get model status")
    logger.info("  - GET    /openarc/metrics            Get hardware telemetry")
    logger.info("  - POST   /openarc/models/update      Update model configuration")
    logger.info("  - POST   /openarc/bench              Run inference benchmark")
    logger.info("  - GET    /openarc/downloader         List active model downloads")
    logger.info("  - POST   /openarc/downloader         Start a model download")
    logger.info("  - DELETE /openarc/downloader         Cancel a model download")
    logger.info("  - POST   /openarc/downloader/pause   Pause a model download")
    logger.info("  - POST   /openarc/downloader/resume  Resume a model download")
    logger.info("--------------------------------")
    logger.info("OpenAI compatible endpoints:")
    logger.info("  - GET    /v1/models")
    logger.info("  - POST   /v1/chat/completions")
    logger.info("  - POST   /v1/audio/transcriptions: Whisper only")
    logger.info("  - POST   /v1/audio/speech: Kokoro only")
    logger.info("  - POST   /v1/embeddings")
    logger.info("  - POST   /v1/rerank")
    

    uvicorn.run(
        "src.server.main:app",
        host=host,
        port=port,
        log_config=LOG_CONFIG,
        reload=reload
    )