"""services/permission_service.py

One owner for the question every team-scoped capability has to ask before it
does anything: may THIS caller see a record that is not their own?

Three roles may: a MANAGER, an HR user, and a company ADMIN. Everyone else
sees their own record and nothing else. That rule was previously spelled out
five separate times — individual_report, team_leave_query_node,
team_attendance_summary_node, team_members_node, complex_manager_task_node —
each with its own copy of "is the caller a manager", which is how the HR and
admin halves came to be missing from all of them at once: there was no single
place to add them.

Where the answer comes from, in order, and every one of them is ALLOW-only:

  1. state["is_manager"] / state["is_hr_role"], resolved once per
     conversation by hr_graph.manager_gate_node from erp-api's
     /api/v1/ai/leave/context ({..., "is_manager": true, "is_hr": false}).
     This is the authority.
  2. A context payload a node has just fetched itself, when it ran without
     the gate (nodes stay callable on their own, and a permission gate that
     passes because its input is missing is the wrong failure mode).
  3. The JWT role claim (dependencies.is_privileged_role), which covers
     manager and HR — and is the ONLY source for admin, because erp-api's
     context response carries no is_admin field.

Tri-state, deliberately. ACCESS_UNKNOWN means erp-api could not be reached
and no other source said yes, which is not the same as "no": the callers
answer it with "I couldn't verify your access" rather than with a denial
that asserts something about this caller's scope on the strength of an
outage. Nothing here ever returns True on a guess, so an outage can only
ever narrow what a caller can see, never widen it.

What this does NOT decide: WHICH employees are in the caller's team. That is
erp-api's, on every call — it scopes each lookup to the caller's own token
and answers 403 with its own message for anyone outside it. This module only
answers whether to make the call at all.
"""
import logging
import re
from typing import Optional

from dependencies import is_privileged_role

logger = logging.getLogger(__name__)


#: The statuses erp-api answers a permission question with. Both are
#: erp-api ANSWERING ("you may not see this"), not erp-api failing, even
#: though the client surfaces them as an exception on the routes that have
#: not opted into reading their body.
_PERMISSION_STATUS_CODES = frozenset({401, 403})

#: erp-api's own refusal wording, for the cases where the status alone does
#: not say it — a 200 or a 500 carrying "You can only view your own team".
#: Matched against erp-api's message, never against the user's query.
_PERMISSION_WORDING_RE = re.compile(
    r"only\s+(?:view|access|see|retrieve)\s+(?:your|their)\s+own"
    r"|cannot\s+retrieve\s+information\s+for\s+other\s+employees"
    r"|not\s+(?:found\s+)?in\s+your\s+team"
    r"|do(?:es)?\s*n[o']?t\s+have\s+(?:the\s+)?permission"
    r"|no\s+permission\b|unauthori[sz]ed|permission\s+denied|access\s+denied"
    r"|only\s+available\s+to\s+managers",
    re.IGNORECASE,
)


def erp_refused_for_permission(exc=None, *, status_code=None, message=None) -> bool:
    """True when an erp-api response means "you are not allowed to see this"
    rather than "the HR system is unwell".

    The distinction decides which of two very different things the user is
    told. Reported live: an employee asking "show my team attendacne" was
    answered "I'm unable to reach the HR system right now — please try again
    shortly." That is an infrastructure sentence for a permission answer: it
    invites a retry that can never succeed, and it hides the actual rule.
    The right answer is the "Not available" card that states what the
    capability needs and what they can still do themselves.

    Reads erp-api's own response — the status it answered with, and the
    message it sent — rather than guessing from the caller's role, so a
    refusal erp-api words in a new way still lands on the status check, and
    a refusal it sends with an unexpected status still lands on the wording.
    """
    if exc is not None:
        status_code = status_code if status_code is not None else getattr(exc, "status_code", None)
        if message is None:
            message = getattr(exc, "erp_message", None)

    if status_code in _PERMISSION_STATUS_CODES:
        return True
    return bool(message and _PERMISSION_WORDING_RE.search(str(message)))

#: erp-api was unreachable and nothing else granted access, so the answer is
#: unknown rather than no. Deliberately the same string as
#: individual_report.MANAGER_UNKNOWN (and what manager_gate_node writes onto
#: the state for both role flags) so the two can be compared directly without
#: this module importing that one — individual_report imports this one, and a
#: cycle between a permission gate and the node it gates is not worth the
#: shared constant. tests pin that they stay equal.
ACCESS_UNKNOWN = "unknown"


def _caller_claims(state: dict, claims: Optional[dict]) -> dict:
    """The caller's JWT claims, decoded if a caller didn't pass them.

    attendance is imported HERE rather than at module scope on purpose:
    attendance_node has its own "may I see this named employee" gate that
    now asks this module, and a module-level import would make that a cycle.
    Nothing else in here needs attendance, so the cost is one lookup on the
    paths that don't already hold the claims.
    """
    if claims is not None:
        return claims
    import services.attendance as attendance_mod
    return attendance_mod._decode_jwt_claims((state or {}).get("bearer_token"))


def may_view_team(state: dict, claims: Optional[dict] = None,
                  context_data: Optional[dict] = None) -> object:
    """True / False / ACCESS_UNKNOWN — may this caller see a team member's
    record?

    `context_data` is the `data` block of a /leave/context response a caller
    has just fetched for itself; pass it so its is_hr half is read too,
    rather than only the is_manager half the nodes used to keep.
    """
    state = state or {}

    if state.get("is_manager") is True or state.get("is_hr_role") is True:
        return True

    if context_data:
        if context_data.get("is_manager") or context_data.get("is_hr"):
            return True

    if is_privileged_role(_caller_claims(state, claims)):
        return True

    # Only now does an unresolved role matter: every ALLOW above has been
    # asked and declined, so the question is whether this is a real "no" or
    # an outage. Either flag being unknown is enough to make the whole
    # answer unknown — the one that is known is False, and the other might
    # not have been.
    if ACCESS_UNKNOWN in (state.get("is_manager"), state.get("is_hr_role")):
        return ACCESS_UNKNOWN

    return False


def may_view_others_leave_balance(state: dict, context_data: Optional[dict] = None) -> bool:
    """May this caller see ANOTHER employee's leave balance? Only an HR user.

    Narrower than may_view_team on purpose (product decision, 2026-09-30): a
    manager sees a report's leave REQUESTS and attendance, but not their
    balance — "You can't see your team's or anyone else's leave balance; if
    needed, contact HR." Before this, a manager's "show me Rahul's leave
    balance" fetched and showed Rahul's balance.

    ALLOW-only like the rest of this module: only an explicit is_hr (from the
    gate's state or a freshly fetched /leave/context) says yes; an unknown role
    is a no here, since the refusal is the safe answer and costs nothing."""
    state = state or {}
    if state.get("is_hr_role") is True:
        return True
    return bool(context_data and context_data.get("is_hr") is True)


def routes_as_manager(state: dict) -> bool:
    """True when classify_node's manager-only LOOKUP shortcuts should fire
    for this caller.

    The same three roles, answered without a round trip: this runs on the
    routing path, where the only cost that may be paid is a JWT decode, and
    where a False simply means the turn falls through to the ordinary
    classifier rather than being refused. The nodes those shortcuts route to
    re-ask may_view_team themselves — this never grants access, it only
    decides which node gets the question.

    ACCESS_UNKNOWN is not an allow here either: it collapses to False, so an
    erp-api outage sends the turn to the general classifier instead of to a
    manager node that would refuse it anyway.
    """
    return may_view_team(state) is True
