from pathlib import Path

from fastapi import APIRouter, Request, Depends, HTTPException
from fastapi.responses import FileResponse
from loguru import logger

from fastpluggy.core.dependency import get_fastpluggy

app_static_router = APIRouter()


@app_static_router.get("/app_static/{module_name}/{file_path:path}")
async def serve_module_static(module_name: str, file_path: str, request: Request, fast_pluggy=Depends(get_fastpluggy)):
    """
    Serve static files for modules (both plugins & domains).
    Example: /app_static/myapp/css/styles.css → looks for `myapp/static/css/styles.css`
    """
    manager = fast_pluggy.get_manager()
    current_module = manager.modules.get(module_name)

    if current_module is None:
        raise HTTPException(status_code=404, detail=f"Module '{module_name}' not found")

    # Use plugin.module_path (source dir) so src-layout packages resolve correctly.
    # Falls back to plugin_state.path (package root) for flat-layout plugins.
    module_path = (current_module.plugin.module_path or current_module.path)
    file_location = Path(module_path) / "static" / file_path
    if file_location.exists() and file_location.is_file():
        logger.debug(f"Serving static file for {module_name}: {file_location}")
        max_age = fast_pluggy.settings.static_cache_max_age
        return FileResponse(
            str(file_location),
            headers={"Cache-Control": f"public, max-age={max_age}"},
        )

    logger.warning(f"Static file not found: {module_name}/{file_path}")
    raise HTTPException(status_code=404, detail=f"Static file not found: {module_name}/{file_path}")
