# Copyright (c) 2025 Patrick Motsch
# All rights reserved.
from fastapi import APIRouter, Response, Depends, Request, Body
from fastapi.responses import FileResponse
from fastapi.staticfiles import StaticFiles
import os
import logging
from pathlib import Path as FilePath
from typing import Dict, Any, List
from fastapi import HTTPException, status

from modules.shared.configuration import APP_CONFIG
from modules.auth import limiter, getCurrentUser
from modules.datamodels.datamodelUam import User
from modules.interfaces.interfaceDbApp import getRootInterface

# Static folder setup - using absolute path from app root
baseDir = FilePath(__file__).parent.parent.parent  # Go up to gateway root
staticFolder = baseDir / "static"
os.makedirs(staticFolder, exist_ok=True)

logger = logging.getLogger(__name__)

router = APIRouter(
    prefix="", tags=["Administration"], responses={404: {"description": "Not found"}}
)

# Mount static files
router.mount(
    "/static", StaticFiles(directory=str(staticFolder), html=True), name="static"
)


@router.get("/")
@limiter.limit("30/minute")
def root(request: Request) -> Dict[str, str]:
    """API status endpoint"""
    # Validate required configuration values
    allowedOrigins = APP_CONFIG.get("APP_ALLOWED_ORIGINS")
    if not allowedOrigins:
        raise HTTPException(
            status_code=500, detail="APP_ALLOWED_ORIGINS configuration is required"
        )

    return {
        "status": "online",
        "message": "Data Platform API is active",
        "allowedOrigins": f"Allowed origins are {allowedOrigins}",
    }


@router.get("/api/environment")
@limiter.limit("30/minute")
def get_environment(
    request: Request, currentUser: Dict[str, Any] = Depends(getCurrentUser)
) -> Dict[str, str]:
    """Get environment configuration for frontend"""
    # Validate required configuration values
    apiBaseUrl = APP_CONFIG.get("APP_API_URL")
    if not apiBaseUrl:
        raise HTTPException(
            status_code=500, detail="APP_API_URL configuration is required"
        )

    environment = APP_CONFIG.get("APP_ENV")
    if not environment:
        raise HTTPException(status_code=500, detail="APP_ENV configuration is required")

    instanceLabel = APP_CONFIG.get("APP_ENV_LABEL")
    if not instanceLabel:
        raise HTTPException(
            status_code=500, detail="APP_ENV_LABEL configuration is required"
        )

    return {
        "apiBaseUrl": apiBaseUrl,
        "environment": environment,
        "instanceLabel": instanceLabel,
        # Add other environment variables the frontend might need
    }


@router.options("/{fullPath:path}")
@limiter.limit("60/minute")
def options_route(request: Request, fullPath: str) -> Response:
    return Response(status_code=200)


@router.get("/favicon.ico")
@limiter.limit("30/minute")
def favicon(request: Request) -> FileResponse:
    favicon_path = staticFolder / "favicon.ico"
    if not favicon_path.exists():
        raise HTTPException(status_code=404, detail="Favicon not found")
    return FileResponse(str(favicon_path), media_type="image/x-icon")
