""""Who is my reporting manager?" - answered from the caller's own leave
requests.

erp-api has no route that returns the caller's manager, but every leave
request carries the person it is with: approver_name and role ("Pending with
John Smith (Manager)" on the leave card). The approver of a request at the
manager stage IS the reporting manager, so that is where the answer comes
from. A pending request is read first - it names whoever approves today -
then decided ones (approved / rejected).

HA-932 D-07: the question reached the LLM classifier, which ran out of tokens
in a new chat (the greeting) and picked the team roster in a long one. Never
guessed: with no request at the manager stage, the reply says it could not
find one.
"""
import logging
import re
from typing import Optional

from langgraph.types import StreamWriter

import services.erp_client as erp_client

logger = logging.getLogger(__name__)

INTENT = "reporting_manager"
#: "How do I contact them?" straight after the answer above. QA QF-02: it went
#: to the classifier, which read "them" as the caller's team and showed the
#: "Your Team - 18 members" roster.
CONTACT_INTENT = "reporting_manager_contact"

# "who is my reporting manager", "who's my manager?", "my line manager",
# "whom do I report to", "who do i report to", "reporting manager name".
_REPORTING_MANAGER_RE = re.compile(
    r"^\s*(?:(?:who|whom|what)(?:'s|\s+is|\s+are)?\s+(?:the\s+name\s+of\s+)?)?"
    r"(?:my|mine)\s+(?:reporting|line|direct|immediate)?\s*(?:manager|supervisor|boss|"
    r"reporting\s+(?:manager|head|authority|person))(?:'s)?(?:\s+name)?\s*[?.!]*\s*$"
    r"|^\s*(?:who|whom)\s+(?:do|should)\s+i\s+report\s+to\s*[?.!]*\s*$"
    r"|^\s*(?:tell\s+me\s+|show\s+me\s+|give\s+me\s+)?(?:my\s+)?reporting\s+manager"
    r"(?:'s)?(?:\s+name)?\s*[?.!]*\s*$"
    # Hinglish: "mera manager kaun hai", "mere reporting manager kon hain",
    # "manager kaun hai mera" (pilot run, 28 Oct: answered with the team list).
    r"|^\s*(?:mera|mere|meri|apna)\s+(?:reporting\s+|line\s+)?(?:manager|supervisor|boss)\s+"
    r"(?:kaun|kon|koun)\s+(?:hai|hain|he|h)\s*[?.!]*\s*$"
    r"|^\s*(?:reporting\s+)?(?:manager|supervisor|boss)\s+(?:kaun|kon|koun)\s+(?:hai|hain|he|h)\s+"
    r"(?:mera|mere|meri)\s*[?.!]*\s*$"
    r"|^\s*(?:main|mai|mein|me)\s+(?:kisko|kise)\s+report\s+(?:karta|karti|karte)\s+(?:hu|hoon|hun|hain)"
    r"\s*[?.!]*\s*$",
    re.IGNORECASE)

NOT_FOUND_MESSAGE = (
    "I couldn't find your reporting manager. I look it up from the approver on your leave "
    "requests, and none of yours is at the manager stage. Your HR team can tell you, or it "
    "will show up here once you have a leave request with your manager.")
_UNREACHABLE_MESSAGE = "I'm unable to reach the HR system right now — please try again shortly."
_TIMEOUT_MESSAGE = "I couldn't reach the HR system in time — please try again in a moment."

# erp-api has no contact details for anyone (no email, phone or chat handle
# on any route), so the contact answer names who and where to look - never
# an address or number, which would be invented.
CONTACT_KNOWN_MESSAGE = (
    "I don't have contact details for **{manager}** here. You can reach them through your "
    "company directory or work email, or ask HR for their contact details.")
CONTACT_NOT_FOUND_MESSAGE = (
    "I couldn't find your reporting manager, so HR is the best place to start - they can "
    "tell you who it is and how to reach them.")
CONTACT_UNREACHABLE_MESSAGE = (
    "I couldn't check who your reporting manager is right now. HR can tell you who it is "
    "and how to reach them.")

# A way of getting in touch, asked about someone: "how do I contact them?",
# "how can I reach him?", "what's her email?", "can I call my manager?".
_CONTACT_VERB_RE = re.compile(
    r"\b(?:contact|reach|get\s+(?:in\s+)?touch|e-?mail|mail|call|phone|ring|message|text|ping|"
    r"talk\s+to|speak\s+(?:to|with)|meet|connect\s+with|number|whatsapp|teams)\b",
    re.IGNORECASE)
_CONTACT_SUBJECT_RE = re.compile(
    r"\b(?:them|they|their|him|his|her|hers|(?:my\s+)?(?:reporting\s+|line\s+)?manager|"
    r"(?:my\s+)?supervisor|(?:my\s+)?boss)\b",
    re.IGNORECASE)


# Typos of the words above, folded before matching. 10k eval (28 Oct): "who is
# my manger", "whoo is my manager", "who is myy manager", "who is my reportig
# manager?" got the team view or "check the HR portal".
_TYPO_FOLDS = (
    (re.compile(r"\b(?:whoo+|wh|woh|hwo)\b", re.IGNORECASE), "who"),
    (re.compile(r"\b(?:myy+|mi|y)\b", re.IGNORECASE), "my"),
    (re.compile(r"\b(?:manger|maneger|managr|mnager|maanger|manageer|managre|mananger)\b", re.IGNORECASE),
     "manager"),
    (re.compile(r"\b(?:reportig|reprting|reportng|repoting|reporitng|reportinng)\b", re.IGNORECASE),
     "reporting"),
)  # "meera" is left alone: it is also a name ("Meera ka manager").


def is_reporting_manager_query(query: str) -> bool:
    text = (query or "").replace("’", "'").replace("‘", "'")
    for pattern, word in _TYPO_FOLDS:
        text = pattern.sub(word, text)
    return bool(_REPORTING_MANAGER_RE.match(text))


def is_contact_followup(query: str, last_intent: Optional[str]) -> bool:
    """True for "how do I contact them?" right after the reporting-manager
    answer (or after an earlier contact answer). Needs both a way of getting
    in touch and the manager as its subject, so "contact HR" or "how do I
    reach the office?" are left to the classifier."""
    if last_intent not in (INTENT, CONTACT_INTENT):
        return False
    text = (query or "").replace("’", "'").replace("‘", "'")
    if len(text.split()) > 12:
        return False
    return bool(_CONTACT_VERB_RE.search(text) and _CONTACT_SUBJECT_RE.search(text))


def _recency(leave: dict) -> tuple:
    try:
        leave_id = int(leave.get("id") or 0)
    except (TypeError, ValueError):
        leave_id = 0
    return (str(leave.get("applied_date") or ""), leave_id)


def manager_from_leaves(leaves: list) -> Optional[str]:
    """The approver of the most recently applied request at the manager
    stage, or None. An HR-stage approver is not the reporting manager, and a
    row with a name but no role does not say which stage it is - neither is
    used.

    Most recent, not first: a reporting manager changes. On QA, /leave/pending
    returned requests from August with Pankaj Singh and from late September
    with Ayush Chandra - the second is who the employee reports to now.
    erp-api happens to list newest first; that is not relied on."""
    for leave in sorted(leaves or [], key=_recency, reverse=True):
        name = str(leave.get("approver_name") or "").strip()
        role = str(leave.get("role") or leave.get("approver_role") or "").strip().lower()
        if name and "manager" in role:
            return name
    return None


async def _lookup_manager(state: dict) -> tuple:
    """(manager name or None, error message or None) from the caller's leave
    requests: /leave/pending first (whoever approves today), then the full
    history from /leave/applied?leave_status=all."""
    company_id = state.get("company_id")
    conversation_id = state.get("conversation_id", "")
    bearer_token = state.get("bearer_token")
    for fetch in (
        lambda: erp_client.get_pending_leaves(
            bearer_token, company_id=company_id, conversation_id=conversation_id),
        lambda: erp_client.get_applied_leaves(
            bearer_token, leave_status="all", company_id=company_id,
            conversation_id=conversation_id),
    ):
        try:
            result = await fetch()
        except erp_client.ErpApiTimeout:
            return None, _TIMEOUT_MESSAGE
        except (erp_client.ErpApiUnavailable, erp_client.ErpApiUnauthorized):
            return None, _UNREACHABLE_MESSAGE
        leaves = ((result or {}).get("body") or {}).get("data", {}).get("leaves") or []
        manager = manager_from_leaves(leaves)
        if manager:
            logger.info("[ReportingManager] found on the caller's leave requests")
            return manager, None
    logger.info("[ReportingManager] no leave request at the manager stage")
    return None, None


async def reporting_manager_node(state: dict, writer: StreamWriter) -> dict:
    usage_events = list(state.get("usage_events", []))
    intent = CONTACT_INTENT if state.get("intent") == CONTACT_INTENT else INTENT

    def _finish(message: str, manager: Optional[str] = None) -> dict:
        data = {"answer": message, "reporting_manager": manager}
        writer({"type": "done", "intent": intent, "is_hr": True,
                "data": data, "message": message, "usage_events": usage_events})
        return {"response_text": message, "usage_events": usage_events}

    manager, error = await _lookup_manager(state)
    if intent == CONTACT_INTENT:
        if manager:
            return _finish(CONTACT_KNOWN_MESSAGE.format(manager=manager), manager)
        return _finish(CONTACT_UNREACHABLE_MESSAGE if error else CONTACT_NOT_FOUND_MESSAGE)
    if error:
        return _finish(error)
    if manager:
        return _finish(f"Your reporting manager is **{manager}**.", manager)
    return _finish(NOT_FOUND_MESSAGE)
