# retoor <retoor@molodetz.nl>

from __future__ import annotations

import json
import logging

from markupsafe import Markup
from starlette.requests import Request

from devplacepy.constants import DEVII_GUEST_COOKIE
from devplacepy.database import get_custom_overrides, get_setting
from devplacepy.utils import get_current_user

logger = logging.getLogger("customization")

EMPTY = Markup("")


def page_type_for(request: Request) -> str:
    route = request.scope.get("route")
    path = getattr(route, "path", None)
    if path:
        return path
    return request.url.path


def owner_for(request: Request) -> tuple[str, str] | None:
    user = get_current_user(request)
    if user:
        return "user", user["uid"]
    guest = request.cookies.get(DEVII_GUEST_COOKIE)
    if guest:
        return "guest", guest
    return None


def _overrides_for(request: Request) -> dict:
    cached = getattr(request.state, "_custom_overrides", None)
    if cached is not None:
        return cached
    overrides = _resolve_overrides(request)
    try:
        request.state._custom_overrides = overrides
    except Exception:
        pass
    return overrides


def _resolve_overrides(request: Request) -> dict:
    if get_setting("customization_enabled", "1") != "1":
        return {"css": "", "js": ""}
    owner = owner_for(request)
    if owner is None:
        return {"css": "", "js": ""}
    return get_custom_overrides(owner[0], owner[1], page_type_for(request))


def custom_css_tag(request: Request) -> Markup:
    try:
        css = _overrides_for(request).get("css", "")
        if not css.strip():
            return EMPTY
        safe = css.replace("</", "<\\/")
        return Markup(f'<style id="user-custom-css">\n{safe}\n</style>')
    except Exception as exc:  # noqa: BLE001 - a customization bug must never break page render
        logger.warning("custom_css_tag failed: %s", exc)
        return EMPTY


def custom_js_tag(request: Request) -> Markup:
    try:
        if get_setting("customization_js_enabled", "1") != "1":
            return EMPTY
        code = _overrides_for(request).get("js", "")
        if not code.strip():
            return EMPTY
        payload = json.dumps(code).replace("<", "\\u003c").replace(">", "\\u003e")
        runner = (
            f'<script type="application/json" id="user-custom-js-src">{payload}</script>'
            "<script>(function(){try{"
            'var src=document.getElementById("user-custom-js-src");'
            "if(src){new Function(JSON.parse(src.textContent))();}"
            '}catch(error){console.error("user custom js error",error);}})();</script>'
        )
        return Markup(runner)
    except Exception as exc:  # noqa: BLE001 - a customization bug must never break page render
        logger.warning("custom_js_tag failed: %s", exc)
        return EMPTY
