import sys

import uvicorn
from fastapi import FastAPI

from src import __version__
from src.api.metrics import metrics_router
from src.api.routers.v1 import router as api_router
from src.core.config import config
from src.core.metrics import create_request_tracker

app = FastAPI(title="Vandamme Proxy", version=__version__)

# Process-local metrics tracking is owned by the FastAPI app instance.
# This avoids module-level singletons and keeps imports side-effect free.
app.state.request_tracker = create_request_tracker()

app.include_router(api_router)
app.include_router(metrics_router, prefix="/metrics", tags=["metrics"])

# Dashboard (Dash) mounted under /dashboard
try:
    from src.dashboard.mount import mount_dashboard

    mount_dashboard(fastapi_app=app)
except ImportError as e:
    # Dashboard dependencies not installed
    print(f"⚠️ Dashboard not mounted: missing dependencies ({e})")
except Exception as e:
    # Other error mounting dashboard
    print(f"⚠️ Dashboard not mounted: {e}")
    import traceback

    traceback.print_exc()


def main() -> None:
    if len(sys.argv) > 1 and sys.argv[1] == "--help":
        print(f"Vandamme Proxy v{__version__}")
        print("")
        print("Usage: python src/main.py")
        print("       or: vdm start")
        print("")
        print("Required environment variables:")
        print("  OPENAI_API_KEY - Your OpenAI API key")
        print("")
        print("Optional environment variables:")
        print("  PROXY_API_KEY - Expected API key for client validation at the proxy")
        print("                      If set, clients must provide this exact API key")
        print("  HOST - Server host (default: 0.0.0.0)")
        print("  PORT - Server port (default: 8082)")
        print("  LOG_LEVEL - Logging level (default: WARNING)")
        print("  MAX_TOKENS_LIMIT - Token limit (default: 4096)")
        print("  MIN_TOKENS_LIMIT - Minimum token limit (default: 100)")
        print("  REQUEST_TIMEOUT - Request timeout in seconds (default: 90)")
        print("")
        print("")
        print("For more options, use the vdm CLI:")
        print("  vdm config show  - Show current configuration")
        print("  vdm config setup - Interactive configuration setup")
        print("  vdm health check - Check API connectivity")
        sys.exit(0)

    # Configure logging FIRST before any console output
    # This suppresses noisy HTTP client logs (openai, httpx, httpcore) unless DEBUG
    from src.core.logging.configuration import configure_root_logging

    configure_root_logging(use_systemd=False)

    # Configuration summary
    print("🚀 Vandamme Proxy v1.0.0")
    print("✅ Configuration loaded successfully")
    print(f"   API Key : {config.api_key_hash}")
    print(f"   Base URL: {config.base_url}")
    print(f"   Max Tokens Limit: {config.max_tokens_limit}")
    print(f"   Request Timeout : {config.request_timeout}s")
    print(f"   Server: {config.host}:{config.port}")
    print(f"   Client API Key Validation: {'Enabled' if config.proxy_api_key else 'Disabled'}")
    print("")

    # Show provider summary
    config.provider_manager.print_provider_summary()

    # Parse log level - extract just the first word to handle comments
    log_level = config.log_level.split()[0].lower()

    # Validate and set default if invalid
    valid_levels = ["debug", "info", "warning", "error", "critical"]
    if log_level not in valid_levels:
        log_level = "info"

    # Start server
    uvicorn.run(
        "src.main:app",
        host=config.host,
        port=config.port,
        log_level=log_level,
        access_log=(log_level == "debug"),  # Only show access logs at DEBUG level
        reload=False,
    )


if __name__ == "__main__":
    main()
