from odoo import models
from odoo.http import request
from odoo.tools.misc import str2bool

ALLOWED_TRANSLATE_MODES = ["", "1"]


class IrHttp(models.AbstractModel):
    _inherit = "ir.http"

    @classmethod
    def _handle_translate(cls):
        """Reads ?translate= from request params and stores in session['translate'].
        Only updates session if the parameter is explicitly present in the request.
        """
        translate = request.httprequest.args.get("translate")
        if translate is not None:
            request.session["translate"] = ",".join(
                mode
                if mode in ALLOWED_TRANSLATE_MODES
                else "1"
                if str2bool(mode, mode)
                else ""
                for mode in (translate or "").split(",")
            )

    @classmethod
    def _pre_dispatch(cls, rule, args):
        """OVERRIDE: calls _handle_translate after super() to store translate in session."""
        res = super()._pre_dispatch(rule, args)
        cls._handle_translate()
        return res

    def session_info(self):
        """OVERRIDE: adds translate to bundle_params in session_info."""
        session_info = super().session_info()
        translate = request.session.get("translate", "")
        if "bundle_params" not in session_info:
            session_info["bundle_params"] = {}
        session_info["bundle_params"]["translate"] = translate
        return session_info
