import logging
import re

from langgraph.graph import END
from langgraph.types import StreamWriter

import services.attendance as attendance_mod
from dependencies import is_manager_role
from services.ai_service import classify_intent_structured
import services.access_notice as access_notice
import services.permission_service as permission_service
from services.classify_node import (
    _score_shift_lookup_query, _REGULARISATION_MARKERS, _REGULARISATION_APPLY_MARKERS,
)
from services.regularisation_guards import (
    APPLY_FOR_OTHERS_NOT_ALLOWED_MESSAGE,
    TEAM_REGULARISATION_VIEW_NOT_ALLOWED_MESSAGE,
)
from services.nlp_service import fast_classify

logger = logging.getLogger(__name__)

#: The done-intent for a refused request about someone else's attendance -
#: alongside team_attendance_restricted and team_members_restricted, so the
#: renderer and history key it the same way. Was the generic "blocked".
ATTENDANCE_RESTRICTED_INTENT = access_notice.RESTRICTED_INTENT


#: Capabilities that are ABOUT the caller's OWN team and carry their own
#: authorization, the way shift_query_node does. Each is scoped by the
#: caller's bearer token at erp-api (the endpoints take no team/target
#: parameter at all), gated on is_manager in its own node, and backstopped by
#: erp-api's authoritative 403 - so reaching the node discloses nothing this
#: guard was protecting.
_TEAM_CAPABILITY_INTENTS = frozenset({
    "HRMS_TEAM_LEAVE_QUERY",
    "HRMS_TEAM_ATTENDANCE_QUERY",
    "HRMS_TEAM_MEMBERS_QUERY",
})


#: The attendance/punch vocabulary this guard exists for. Typo-tolerant on
#: "atten..." like the rest of the codebase; "come in"/"came in"/"leave the
#: office" cover the arrival/departure phrasing that has no attendance word.
_ATTENDANCE_SCOPE_RE = re.compile(
    r"\batten\w*|\bpunch\w*|\bcheck(?:ed)?[\s-]?(?:in|out)s?\b|\bclock(?:ed)?[\s-]?(?:in|out)\b"
    r"|\blog(?:ged)?[\s-]?(?:in|out)\b|\blogin|\blogout|\bpresent\b|\babsen\w*|\blate\b"
    r"|\bwork(?:ed|ing)?\s+hours\b|\bin[\s-]?time\b|\bout[\s-]?time\b|\btimesheet"
    r"|\b(?:come|came|coming)\s+in\b|\bleft\s+(?:the\s+)?office\b|\bwfh\b|\bwork\s+from\s+home\b"
    r"|\bregulari\w*"
    # Attendance status words with no "attendance" in them ("why was John
    # marked half-day"), and shift/roster phrasing the shift exemption above
    # deliberately does not cover ("can I change my shift").
    r"|\bhalf[\s-]?days?\b|\bfull[\s-]?days?\b|\bmarked\b|\bovertime\b|\bearly\b|\bon\s+time\b"
    r"|\bshifts?\b|\broster\w*|\brota\b",
    re.IGNORECASE,
)


def _is_regularisation_view_query(query: str) -> bool:
    """True when the refused question is about SEEING regularization
    requests rather than attendance — so the refusal is erp-api's own
    "Only Manager/HR users can view team regularization requests." instead of
    the attendance-worded one. Applying for one on someone else's behalf is
    not a view and keeps the attendance wording."""
    ql = (query or "").lower()
    return (any(m in ql for m in _REGULARISATION_MARKERS)
            and not any(m in ql for m in _REGULARISATION_APPLY_MARKERS))


def _is_regularisation_apply_query(query: str) -> bool:
    """True when the refused request is APPLYING for a regularization."""
    ql = (query or "").lower()
    return (any(m in ql for m in _REGULARISATION_MARKERS)
            and any(m in ql for m in _REGULARISATION_APPLY_MARKERS))


def _is_own_team_capability_query(query: str) -> bool:
    """True for an unambiguous question about the caller's own team.

    Deterministic on purpose: this decides whether an LLM label gets to
    hard-block the turn, so it must not itself depend on an LLM call that
    can answer differently run to run.
    """
    intent, _is_hr, confidence = fast_classify(query or "")
    return intent in _TEAM_CAPABILITY_INTENTS and confidence >= 0.5


def _mentions_own_identity(query: str, current_name, current_emp_no) -> bool:
    """True when the query names the CALLER, by their own full name or
    employee number (both read off the JWT, same claims attendance.py's own
    ownership check already reads — see _decode_jwt_claims).

    Confirmed live bug: this guard runs BEFORE classify_node, attendance_
    node, punch_details_node and regularisation_node — literally the first
    node after START — and its own LLM classifier has NO knowledge of who
    the caller is (the prompt only ever sees the bare query text). Its own
    example set says a query naming ANYONE is "other" unless no name
    appears at all, so "show attendance for Akash Jio" asked BY Akash Jio
    reliably classified as "other" and got hard-blocked here — before ever
    reaching attendance_node's own ownership check (_is_authorized_for_
    target), which DOES correctly recognize a self-name-match, but never
    got the chance to run at all.

    Deliberately requires the caller's FULL name (not a single first/last-
    name token) to appear as a contiguous phrase — matching this file's own
    existing _names_match's reasoning against "Sam" wrongly matching
    "Samantha": a bare single-token match ("Akash" alone) risks a false
    self-match when the query actually names a DIFFERENT employee who
    happens to share one name token with the caller (e.g. caller "Akash
    Jio" asking about report "Akash Kumar"). An exact emp_no token match is
    unambiguous by construction (a company-unique code), so no such
    restriction applies there.
    """
    q = (query or "").lower()

    if current_name:
        name_norm = " ".join(str(current_name).strip().lower().split())
        if name_norm and re.search(rf"\b{re.escape(name_norm)}\b", q):
            return True

    if current_emp_no:
        emp_no_norm = str(current_emp_no).strip().lower()
        if emp_no_norm and re.search(rf"\b{re.escape(emp_no_norm)}\b", q):
            return True

    return False


# Ownership guardrail: detect requests for OTHER people's data (a named
# employee, a group/team, or a manager/boss) and deny them early, before
# expensive LLM classification — unless the caller holds a privileged role
# (HR/manager/admin) as determined from their JWT claims, in which case the
# request is allowed to proceed to the downstream nodes (team/individual
# report handlers) that apply their own finer-grained role checks.

async def ownership_guard_node(state: dict, writer: StreamWriter) -> dict:
    """Pre-classify node: detect queries that request OTHER employees'
    attendance/punch data (named employee, group/team, or manager/boss)
    and block them with a polite message — unless the caller has a
    privileged role, in which case it's allowed through to classification.
    """
    query = state.get("query", "") or ""
    bearer = state.get("bearer_token")

    # This guard is scoped to ATTENDANCE/PUNCH data (see its own prompt and
    # docstring). A shift-assignment question is a different feature with
    # its own permission gate: classify_node routes it to shift_query_node,
    # which applies its own check and returns the shift-worded refusal
    # ("I can only provide shift details for your own account.", intent
    # "shift_query", denied=true) for a named target — every role alike,
    # no manager/HR exception. Blocking it here would pre-empt all of that
    # with an attendance-worded message and intent "blocked". So let every
    # shift-lookup phrasing straight through to classification, targeted
    # or not.
    #
    # _score_shift_lookup_query (not the narrower _is_shift_lookup_query,
    # deliberately) — that "certain tier" only phrase list missed unmistakably
    # shift-shaped asks like "show me the shift for X" or "tell me A Sharma
    # shift" (no "'s", no "shift details" phrase), which fell through to this
    # guard's own attendance-scoped classifier, correctly saw a named OTHER
    # employee, and blocked with the ATTENDANCE-worded refusal instead of ever
    # reaching shift_query_node's own shift-worded one. A non-zero score here
    # doesn't promise classify_node will actually route to shift_query (that
    # still runs its own, possibly LLM-backed, adjudication) — it only means
    # there is real shift vocabulary in play, which is enough to say this
    # guard's own attendance-only classifier is the wrong tool to judge it.
    if _score_shift_lookup_query(query.lower()) > 0.0:
        return {"blocked": False}

    # Same reasoning as the shift exemption above, for the caller's own TEAM.
    #
    # Live bug: "show my team pending leaves" from a non-manager classified
    # as "group" and was hard-blocked right here - with the ATTENDANCE
    # wording, for a LEAVE question, under intent "blocked". It never reached
    # team_leave_query_node, whose own gate answers with the "Not available"
    # card (services/access_notice.py) that states the actual rule.
    #
    # It broke MANAGERS too, intermittently: the block below denies
    # "group" for anyone whose is_manager isn't already True on the state,
    # and the label comes from an LLM - so the identical query passed or
    # failed run to run depending on whether it came back "self" (from "my")
    # or "group" (from "team").
    #
    # This widens no access. Every one of these endpoints resolves "my team"
    # from the bearer token and takes no target parameter, so there is no
    # other team to ask about; the nodes keep their own manager gate and
    # erp-api keeps its 403. All that changes is WHICH refusal a
    # non-manager sees.
    if _is_own_team_capability_query(query):
        return {"blocked": False}

    # Out of scope entirely: nothing about attendance/punch data. This guard
    # ran on EVERY query, and its classifier labels anything plural or
    # company-wide as "group" - live: "Total Company Leave" (a policy
    # question) was refused as someone else's attendance. Leave, policy and
    # HR questions go to classification; attendance_node still applies its
    # own named-target check (_is_authorized_for_target) either way.
    if not _ATTENDANCE_SCOPE_RE.search(query):
        return {"blocked": False}

    # A company-rule question ("what are the standard working hours") uses
    # the scope vocabulary above but asks about nobody - the classifier below
    # could read "company-wide" as "group" and refuse it.
    if fast_classify(query)[0] == "policy":
        return {"blocked": False}

    # Checked BEFORE any LLM call — see _mentions_own_identity's own
    # docstring for the live bug this closes: the classifier below has no
    # idea who the caller is, so a query naming the caller BY THEIR OWN
    # name or employee number (both already sit in their JWT) would
    # otherwise reliably classify as "other" and get hard-blocked here,
    # never even reaching attendance_node/punch_details_node/
    # regularisation_node's own (already-correct) self-name handling.
    claims = attendance_mod._decode_jwt_claims(bearer)
    current_name = claims.get("name") or claims.get("username") or claims.get("preferred_username")
    current_emp_no = claims.get("emp_no")
    if _mentions_own_identity(query, current_name, current_emp_no):
        return {"blocked": False}

    # Prefer provider-backed classification (OpenAI) for robust detection
    # of whether the user asks about themselves or others. Falls back to
    # deterministic regex when OpenAI isn't the active provider.
    labels = frozenset({"self", "other", "group", "manager", "unknown"})
    prompt = (
        "You are classifying the INTENT of a workplace query about attendance/punch data.\n"
        "Categories:\n"
        "- self: the user is asking about their OWN attendance (no other name/employee mentioned, "
        "uses 'my', 'me', 'I', or no subject at all)\n"
        "- other: the user names or clearly refers to ONE specific other employee (by name or "
        "explicit reference like 'John's attendance')\n"
        "- group: the user asks about multiple employees, a team, department, or 'all employees'\n"
        "- manager: the user asks about their manager's/boss's attendance\n"
        "- unknown: intent cannot be determined\n\n"
        "IMPORTANT: If no employee name is mentioned and no group/manager keywords appear, "
        "default to 'self'.\n\n"
        "Examples:\n"
        "Query: 'give me attendance for last week' -> {\"intent\": \"self\"}\n"
        "Query: 'show my punch details for July' -> {\"intent\": \"self\"}\n"
        "Query: 'what is John's attendance this month' -> {\"intent\": \"other\"}\n"
        "Query: 'attendance for the sales team' -> {\"intent\": \"group\"}\n"
        "Query: 'when did my manager clock in yesterday' -> {\"intent\": \"manager\"}\n\n"
        "Respond ONLY with JSON: {\"intent\": \"self|other|group|manager|unknown\"}.\n"
        f"Current query: {query}"
    )

    try:
        label, usage, _ = await classify_intent_structured(prompt, labels, fallback_label="unknown")
    except Exception as e:
        logger.warning(f"[Guard] ownership classifier failed: {e}")
        label = "unknown"

    # "other"/"group"/"manager" all name someone besides the caller — allow
    # them through only if the caller holds a privileged role (HR/manager/
    # admin), same as the existing named-employee check in attendance.py's
    # _is_authorized_for_target(). Non-privileged callers are still denied.
    if label in ("other", "group", "manager"):
        # manager_gate_node runs immediately before this node and has already
        # resolved is_manager authoritatively — the JWT role claim first
        # (is_manager_role), then erp-api when the token doesn't say. Trust
        # that result before re-deriving anything here: is_manager_role is a
        # fast-path ALLOW only, and its own docstring is explicit that False
        # means "the token didn't say", the normal case for every token
        # issued today, with erp-api the only real authority. Re-running just
        # the JWT half below would therefore answer False for a real manager
        # and block the very features (individual_report, leave_approval,
        # team queries) meant to reach a named report's record. Tri-state on
        # purpose: only an explicit True allows — MANAGER_UNKNOWN (erp-api
        # unreachable) falls through to the checks below rather than opening
        # the guard.
        # A manager, an HR user or an admin may ask about someone else —
        # one rule, in services/permission_service, rather than this node's
        # own reading of the role. Everything below stays as the narrower
        # fallback for a caller the graph has not resolved at all.
        if permission_service.may_view_team(state, claims=attendance_mod._decode_jwt_claims(bearer)) is True:
            return {"blocked": False}
        try:
            claims = attendance_mod._decode_jwt_claims(bearer)
            # dependencies.is_manager_role() recognizes the role by NAME
            # ("manager", "reporting_manager", ...) — this used to be checked
            # only against attendance.PRIVILEGED_ROLES, a purely numeric
            # role_id set ({"1","2","3","4"}), which meant a token carrying
            # role: "manager" as a string (no matching numeric role_id) was
            # denied here even though every other manager-only node in this
            # graph (manager_gate_node, individual_report.py, leave_approval.py)
            # already treats that exact claim as sufficient. Checked first
            # since it is the cheaper, more common case for today's tokens.
            if is_manager_role(claims):
                return {"blocked": False}
            role = claims.get("role") or claims.get("roles") or claims.get("role_id")
            roles = role if isinstance(role, (list, set, tuple)) else [role]
            if any(r is not None and str(r).strip().lower() in attendance_mod.PRIVILEGED_ROLES for r in roles):
                return {"blocked": False}
        except Exception:
            pass
        _message = ("Sorry, I can only share attendance details for your own account — "
                    "for someone else's, please check with HR or your manager.")
        _capability = "other_employee_attendance"
        if _is_regularisation_view_query(query):
            _message = TEAM_REGULARISATION_VIEW_NOT_ALLOWED_MESSAGE
            _capability = "other_employee_regularization"
        elif _is_regularisation_apply_query(query):
            # Applying for someone else is refused for every role, with the
            # same sentence classify_node gives a manager - not the
            # attendance wording, which answered a question nobody asked.
            _message = APPLY_FOR_OTHERS_NOT_ALLOWED_MESSAGE
            _capability = "other_employee_regularization_apply"
        # The "Access restricted" card and its own intent ride on the refusal.
        # QA: this went out as a bare guardrail with intent "blocked", so the
        # UI drew a plain bubble - not the card the design shows for someone
        # else's record. main.py forwards `access_notice` as the card event and
        # uses `intent` for the done event (and the saved message, so history
        # renders it the same way). Role came from may_view_team above - the
        # /leave/context is_manager / is_hr the manager gate resolved.
        writer({
            "type": "guardrail",
            "stage": "input",
            "status": "failed",
            "categories": ["privacy"],
            "message": _message,
            "intent": ATTENDANCE_RESTRICTED_INTENT,
            "access_notice": access_notice.build_restricted(_capability, _message),
        })
        return {"blocked": True}

    # self or unknown → continue to classification (unknown is allowed to proceed)
    return {"blocked": False}


def _route_after_ownership(result: dict) -> str:
    """Routes to END when ownership guard blocked, otherwise to classify_node."""
    if result.get("blocked"):
        return END
    return "classify_node"