"""

Public site on erp.* (ERP_ONLY): landing at /, login/setup linked from there.

Legacy apex hosts redirect to erp origin until cnpsolutions.co.bw DNS is moved.

"""

from __future__ import annotations



import os

from starlette.middleware.base import BaseHTTPMiddleware

from starlette.requests import Request

from starlette.responses import RedirectResponse, Response





def _env_bool(key: str, default: str = "") -> bool:

    return os.environ.get(key, default).strip().lower() in ("1", "true", "yes", "on")





def _hosts(env_key: str, default: str) -> frozenset[str]:

    raw = os.environ.get(env_key, default)

    return frozenset(h.strip().lower() for h in raw.split(",") if h.strip())





ERP_ONLY = _env_bool("ERP_ONLY")

MARKETING_HOSTS = _hosts(

    "MARKETING_HOSTS",

    "cnpsolutions.co.bw,www.cnpsolutions.co.bw",

)

ERP_HOSTS = _hosts("ERP_HOSTS", "erp.cnpsolutions.co.bw")

MARKETING_ORIGIN = os.environ.get("MARKETING_PUBLIC_URL", "https://cnpsolutions.co.bw").rstrip("/")

ERP_ORIGIN = os.environ.get("ERP_PUBLIC_URL", "https://erp.cnpsolutions.co.bw").rstrip("/")



MARKETING_STATIC_HTML = frozenset({"cnp-solutions.html"})

MARKETING_API_PREFIXES = ("/api/v1/installer/download",)





def _erp_url(path: str, query: str) -> str:

    if query:

        return f"{ERP_ORIGIN}{path}?{query.lstrip('?')}"

    return f"{ERP_ORIGIN}{path}"





def _marketing_url(path: str, query: str) -> str:

    if query:

        return f"{MARKETING_ORIGIN}{path}?{query.lstrip('?')}"

    return f"{MARKETING_ORIGIN}{path}"





class HostRoutingMiddleware(BaseHTTPMiddleware):

    async def dispatch(self, request: Request, call_next) -> Response:

        host = (request.headers.get("host") or "").split(":")[0].lower()

        path = request.url.path

        query = request.url.query



        if ERP_ONLY:

            # Apex not in use yet — send old hostname traffic to erp (same path, landing at /)

            if host in MARKETING_HOSTS:

                if any(path.startswith(p) for p in MARKETING_API_PREFIXES):

                    return await call_next(request)

                return RedirectResponse(_erp_url(path or "/", query), status_code=302)

            return await call_next(request)



        if host in MARKETING_HOSTS:

            if path in ("/", "/home"):

                return await call_next(request)

            if path.startswith("/static/") and path.endswith(".html"):

                name = path.rsplit("/", 1)[-1]

                if name not in MARKETING_STATIC_HTML:

                    return RedirectResponse(_erp_url(path, query), status_code=302)

                return await call_next(request)

            if path.startswith("/static/"):

                return await call_next(request)

            if any(path.startswith(p) for p in MARKETING_API_PREFIXES):

                return await call_next(request)

            return RedirectResponse(_erp_url(path, query), status_code=302)



        if host in ERP_HOSTS:

            if path == "/home":

                return RedirectResponse(_marketing_url("/", query), status_code=302)

            if path == "/static/cnp-solutions.html" or path.endswith("/cnp-solutions.html"):

                return RedirectResponse(_marketing_url("/", query), status_code=302)



        return await call_next(request)


