import os
from fastapi import Request
from fastapi.responses import FileResponse
from starlette.middleware.base import BaseHTTPMiddleware
import pkg_resources

STATICS_DIR = pkg_resources.resource_filename("mineru_flow.internal", "statics")
INDEX_HTML_PATH = os.path.join(STATICS_DIR, "index.html")
PUBLIC_PREFIXES = ("/assets", "/static", "/favicon", "/robots")


class ContentTypeMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next):
        path = request.url.path

        if path.startswith("/api"):
            response = await call_next(request)
            # set content-type for javascript files
            if path.endswith(".js"):
                response.headers["content-type"] = "application/javascript"
            return response

        if request.method != "GET":
            return await call_next(request)

        if any(path.startswith(prefix) for prefix in PUBLIC_PREFIXES) or "." in os.path.basename(path):
            return await call_next(request)

        return FileResponse(
            INDEX_HTML_PATH,
            status_code=200,
            headers={
                "Content-Type": "text/html",
                "Cache-Control": "no-cache",
                "Connection": "keep-alive",
            },
        )
