import re

from odoo.http import request
from odoo.addons.web.controllers.home import Home

# core's Home._login_redirect(uid, redirect=None) -> _get_login_redirect_url,
# which returns '/odoo' for a fully-authenticated internal user with no
# explicit `redirect` requested, or `redirect` verbatim otherwise. The one
# branch worth overriding: a fully-logged-in phone whose resolved target is
# (or trivially normalizes to) the bare '/odoo' home -- sent straight to the
# Odoo Mobile Attendance page instead of the regular desktop home screen.
# Any other outcome (a genuine deep-link redirect, portal user, MFA partial
# session) is left completely alone.
#
# PHONES ONLY -- a tablet or laptop is treated as desktop (no redirect, and
# the sidebar hides the Odoo Mobile app there too; see navbar_patch.js's
# xenoVisibleApps). Android tablets omit "Mobile" from their UA, so requiring
# "Android.*Mobile" excludes them; iPad is excluded explicitly since modern
# iPadOS Safari still carries "Mobile" in its UA string.
PHONE_USER_AGENT_RE = re.compile(r"iPhone|iPod|Windows Phone|Android.*Mobile|Mobi", re.IGNORECASE)
TABLET_USER_AGENT_RE = re.compile(r"iPad", re.IGNORECASE)


class XenoMobileHome(Home):

    def _login_redirect(self, uid, redirect=None):
        result = super()._login_redirect(uid, redirect=redirect)
        # Bug found in testing: a bookmarked/QR-code login link commonly
        # carries a literal "?redirect=/odoo" (or "/odoo?", "/odoo/") --
        # core's own _get_login_redirect_url returns `redirect` verbatim
        # whenever it's truthy, so that request came back as "/odoo?", not
        # the bare "/odoo" the original `result == "/odoo" and not
        # redirect` check required -- both conditions failed at once, so a
        # phone logging in through that exact link never got the Odoo
        # Mobile redirect at all, only a bare "/web/login" (no redirect
        # param) did. Stripping trailing "/"/"?" normalizes any of these
        # trivial "just go home" variants down to "/odoo" for the
        # comparison; anything that normalizes to something ELSE (a real
        # deep link, e.g. "/odoo/action-45" or "/odoo?debug=1") still
        # doesn't match and is left completely alone.
        normalized = (result or "").rstrip("/?")
        if normalized == "/odoo":
            user_agent = request.httprequest.headers.get("User-Agent", "")
            is_phone = (PHONE_USER_AGENT_RE.search(user_agent)
                        and not TABLET_USER_AGENT_RE.search(user_agent))
            if is_phone:
                action = request.env["ir.actions.client"].sudo().search(
                    [("tag", "=", "xeno_mobile_attendance")], limit=1)
                if action:
                    return f"/odoo/action-{action.id}"
        return result
