"""
Block local/hybrid ERP traffic until the install is activated with a valid CNP license.
Setup, licensing, and health endpoints remain available.
"""
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
from starlette.responses import JSONResponse, RedirectResponse

from app.core.config import settings
from app.services.local_server_license import is_local_deployment, local_server_license_status

_OPEN_PREFIXES = (
    "/static/vendor",
    "/static/icons",
    "/static/images",
    "/static/js/api-error-log.js",
    "/static/js/cnperp-core.js",
)

_OPEN_STATIC_PAGES = {
    "/static/company-setup.html",
    "/static/login.html",
    "/static/cnp-solutions.html",
    "/static/license-subscription.html",
    "/static/contact-support.html",
    "/static/faq.html",
    "/static/about.html",
    "/static/keyboard-shortcuts.html",
    "/static/documentation.html",
    "/static/tutorials.html",
    "/static/help/dimensional-balances-guide.html",
}

_OPEN_EXACT = {
    "/",
    "/health",
    "/setup",
    "/home",
    "/install/local",
    "/api/v1/companies/check-setup",
    "/api/v1/companies/register",
    "/api/v1/companies/register-full",
    "/api/v1/licensing/validate",
    "/api/v1/licensing/verify-setup",
    "/api/v1/licensing/claim-setup",
    "/api/v1/licensing/status",
    "/api/v1/installer/local",
    "/api/v1/installer/validate-download",
    "/api/v1/installer/activation-status",
    "/api/v1/licensing/subscription",
    "/api/v1/licensing/upgrade",
    "/api/v1/licensing/upgrade/preview",
    "/api/v1/licensing/plan-features",
    "/api/v1/public/contact/info",
    "/api/v1/public/contact",
}


class LocalServerLicenseMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next):
        if not is_local_deployment() or not settings.license_enforcement:
            return await call_next(request)

        path = request.url.path
        if self._is_open(path):
            return await call_next(request)

        status = local_server_license_status()
        if status.get("active"):
            return await call_next(request)

        message = status.get("message", "A valid CNP license is required for this local server.")

        if path.startswith("/api/"):
            return JSONResponse(
                status_code=402,
                content={
                    "success": False,
                    "error": "local_server_unlicensed",
                    "status": status.get("status"),
                    "message": message,
                },
            )

        if path.startswith("/static/") and path.endswith(".html"):
            return RedirectResponse(url="/setup", status_code=302)

        return RedirectResponse(url="/setup", status_code=302)

    def _is_open(self, path: str) -> bool:
        if path in _OPEN_EXACT:
            return True
        if path.startswith("/api/v1/companies/lookup/"):
            return True
        if path in _OPEN_STATIC_PAGES:
            return True
        if path.startswith(_OPEN_PREFIXES):
            return True
        if path.startswith("/static/") and (
            path.endswith(".css")
            or path.endswith(".js")
            or path.endswith(".png")
            or path.endswith(".jpg")
            or path.endswith(".ico")
            or path.endswith(".woff2")
            or path.endswith(".woff")
            or path.endswith(".map")
        ):
            return True
        return False
