import logging

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

import services.attendance as attendance_mod
from services.ai_service import classify_intent_structured

logger = logging.getLogger(__name__)


# Ownership guardrail: detect broad requests for OTHER people's data and
# deny them early, before expensive LLM classification. Manager/boss
# requests are allowed to proceed only if the caller holds a privileged
# role (HR/manager/admin) as determined from their JWT claims.

async def ownership_guard_node(state: dict, writer: StreamWriter) -> dict:
    """Pre-classify node: detect queries that clearly request OTHER
    employees' attendance/punch data and block them with a polite message.

    If the query mentions a manager/boss, allow it to proceed only when
    the caller has a privileged role — otherwise deny it here to avoid
    routing to the graph and LLM.
    """
    query = state.get("query", "") or ""
    bearer = state.get("bearer_token")

    # 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"

    # Block or allow based on label
    if label in ("other", "group"):
        writer({
            "type": "guardrail",
            "stage": "input",
            "status": "failed",
            "categories": ["privacy"],
            "message": "Sorry, I can only share attendance details for your own account — for someone else's, please check with HR or your manager.",
        })
        return {"blocked": True}

    if label == "manager":
        # Allow only if caller is privileged
        try:
            claims = attendance_mod._decode_jwt_claims(bearer)
            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
        writer({
            "type": "guardrail",
            "stage": "input",
            "status": "failed",
            "categories": ["privacy"],
            "message": "Sorry, I can only share attendance details for your own account — for someone else's, please check with HR or your manager.",
        })
        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"
