"""services/my_regularisation_view.py

"Show my regularization requests" - the EMPLOYEE's own attendance
regularization requests, every status, newest first.

Why this exists as its own node
-------------------------------
There was no read path for an employee's own requests at all. The word
"regularization" in a query matched the APPLY flow, so "show my
regularization request" opened the submit form and asked "which date(s)
would you like to regularize?" - the assistant offering to create a new
request when the user asked to see the ones they already had.

The manager queue (regularisation_approval.py) could not answer it either:
erp-api scopes that route to the caller's direct reports, excludes the
caller themselves, and refuses a non-manager outright. So this node calls
erp_client.get_my_regularizations() - GET /api/v1/ai/regularizations with no
type param, which since HA-697 answers the caller's own requests.

"my pending regularizations" / "show approved regularization requests" pass
that status through as erp-api's own ?status= filter (see
_requested_status_filter) instead of filtering rows here.

Read-only by construction: nothing here submits, edits, approves or
cancels anything. Acting on a request stays with the flows that own it.
"""
import difflib
import logging
import os
import re
from datetime import datetime
from typing import Optional
from zoneinfo import ZoneInfo

from langgraph.types import StreamWriter

import services.date_query_resolver as date_query_resolver
import services.erp_client as erp_client
import services.permission_service as permission_service
from services import slot_store
from services.regularisation_display import display_date, employee_actions, enrich_rows, status_key
from services.nlp_service import fold_regularization_typos, fold_smart_punctuation

logger = logging.getLogger(__name__)

VIEW_INTENT = "my_regularisation_view"

# How many rows a chat reply lists before saying "and N more". Same number the
# manager queue and the team leave list use, so every list in the assistant
# truncates the same way.
_LIST_LIMIT = 3

NONE_FOUND_MESSAGE = "You don't have any regularization requests yet."

# A status word naming WHICH requests to list: "my pending regularizations",
# "show approved regularization requests". Only when the word sits just
# before "regulari..." - "has my regularization been approved?" asks about a
# request's status, and filtering that to approved rows would answer "none"
# for a request that is merely still pending.
#
# Live: "show my pending reqgulariztion" listed every status. The status word
# was only looked for right before "regulari...", which the typo hid. Now:
#   * regularization typos are folded first (nlp_service), and status-word
#     typos too ("pendng", "aproved", "cancled", "rejectd");
#   * the status word may sit anywhere ("my regularizations that are pending");
#   * a yes/no QUESTION ("has my regularization been approved?", "are my
#     regularizations approved?") is still not a filter;
#   * "pending approval" is pending, and naming two statuses at once
#     ("pending and approved") lists everything rather than half of it.
_STATUS_WORDS = ("pending", "approved", "rejected", "cancelled")
_STATUS_ALIASES = {"canceled": "cancelled", "cancel": "cancelled", "cancelations": "cancelled",
                   "cancellations": "cancelled", "approve": "approved", "reject": "rejected",
                   "rejections": "rejected",
                   # QA: "Show my withdrawn regularizations" listed every request.
                   # A withdrawn regularization is a cancelled one (the
                   # employee's own cancel), so these mean the cancelled filter.
                   "withdrawn": "cancelled", "withdrew": "cancelled", "withdraw": "cancelled",
                   "withdrawals": "cancelled", "retracted": "cancelled", "revoked": "cancelled"}

#: Row statuses each filter shows. "cancelled" also covers a row erp-api labels
#: "withdrawn", so asking for either never hides the other.
_FILTER_STATUSES = {"cancelled": ("cancelled", "withdrawn")}
_STATUS_TYPO_CUTOFF = 0.8
_YES_NO_QUESTION_RE = re.compile(r"^\s*(?:has|have|is|was|were|are|did|does|do)\b", re.IGNORECASE)
_WORD = re.compile(r"[a-z]+")


def _status_word(word: str) -> Optional[str]:
    if word in _STATUS_WORDS:
        return word
    if word in _STATUS_ALIASES:
        return _STATUS_ALIASES[word]
    if len(word) < 5:
        return None
    best = difflib.get_close_matches(word, _STATUS_WORDS, n=1, cutoff=_STATUS_TYPO_CUTOFF)
    return best[0] if best else None


def _requested_status_filter(query: str) -> Optional[str]:
    """pending / approved / rejected / cancelled, or None for every status."""
    text = fold_regularization_typos(fold_smart_punctuation((query or "").lower()))
    if _YES_NO_QUESTION_RE.search(text):
        return None
    found = []
    for word in _WORD.findall(text):
        # "pending approval" names ONE status: the request is pending.
        if word in ("approval", "approvals") and "pending" in found:
            continue
        status = _status_word(word)
        if status and status not in found:
            found.append(status)
    return found[0] if len(found) == 1 else None


def _newest_first(rows: list) -> list:
    """AC-01 lists most recent first — most recently APPLIED, which is the
    order erp-api answers in (created_at, then id). Not apply_date: a request
    applied today for a date two months back is still the newest request.
    Sorting again costs nothing and keeps the order a property of this reply
    rather than of whatever erp-api happens to return."""
    def key(row):
        return (str(row.get("created_at") or ""), _as_int(row.get("regularization_id")))
    return sorted(rows, key=key, reverse=True)


def _as_int(value) -> int:
    try:
        return int(value)
    except (TypeError, ValueError):
        return 0

ERP_UNAVAILABLE_MESSAGE = (
    "I'm unable to reach the HR system right now - please try again shortly."
)
ERP_TIMEOUT_MESSAGE = (
    "I couldn't reach the HR system in time - please try again in a moment."
)


def _time_span(row: dict) -> str:
    """"10:05 to 19:00" - erp-api sends H:i:s, and the seconds are noise."""
    def trim(value) -> str:
        text = str(value or "").strip()
        parts = text.split(":")
        return ":".join(parts[:2]) if len(parts) >= 2 else text

    start, end = trim(row.get("from_time")), trim(row.get("to_time"))
    if start and end:
        return f"{start} to {end}"
    return start or end or ""


def _render_row(row: dict) -> str:
    """One enriched row (see regularisation_display.enrich_row)."""
    span = _time_span(row)
    bits = [str(row.get("apply_date_display") or row.get("apply_date") or "")]
    if span:
        bits.append(span)
    line = ", ".join(b for b in bits if b)
    kind = f" - {row['regularization_type']}" if row.get("regularization_type") else ""
    status = str(row.get("status_label") or row.get("status_name") or "Pending")
    reason = str(row.get("reason") or "").strip()
    tail = f" - {reason}" if reason else ""
    ref = row.get("reference_id") or f"ID {row.get('regularization_id')}"
    applied_on = f", applied {row['applied_on_display']}" if row.get("applied_on_display") else ""
    return f"- {line}{kind} - {status}{tail} (Ref: {ref}{applied_on})"


def _render_list(rows: list, status_filter: Optional[str] = None,
                 span_label: Optional[str] = None) -> str:
    shown = rows[:_LIST_LIMIT]
    count = len(rows)
    qualifier = f"{status_filter} " if status_filter else ""
    when = f" {span_label}" if span_label else ""
    header = (
        f"Here is your {qualifier}regularization request{when}:"
        if count == 1
        else f"Here are your {count} {qualifier}regularization requests{when}:"
    )
    body = "\n".join(_render_row(r) for r in shown)
    if count > _LIST_LIMIT:
        body += f"\n({count - _LIST_LIMIT} more not shown)"
    return f"{header}\n{body}"


# "REG-131", "REG 131", "request id 131", "#131" - one request by reference.
_REFERENCE_RES = (
    re.compile(r"\bREG[\s-]*(\d+)\b", re.IGNORECASE),
    re.compile(r"\brequest\s*(?:id|no\.?|number)\s*#?\s*(\d+)\b", re.IGNORECASE),
    re.compile(r"(?<![\w-])#(\d+)\b"),
)


def _requested_reference(query: str) -> Optional[int]:
    for pattern in _REFERENCE_RES:
        match = pattern.search(query or "")
        if match:
            return int(match.group(1))
    return None


def _today():
    return datetime.now(ZoneInfo(os.getenv("QUOTA_TIMEZONE", "UTC"))).date()


def _requested_dates(query: str, today) -> Optional[tuple]:
    """(from, to) dates the question narrows to - "for 29 sept" (one day),
    "in september", "last month", "from 1 sept to 15 sept" - or None.
    Deterministic, via the same date_query_resolver the other flows use."""
    resolved = date_query_resolver.resolve(query or "", today)
    if not isinstance(resolved, dict):
        return None
    if resolved.get("type") == "single":
        return resolved["date"], resolved["date"]
    if resolved.get("type") == "range":
        return resolved["start_date"], resolved["end_date"]
    return None


def _in_dates(row: dict, span: tuple) -> bool:
    try:
        day = datetime.strptime(str(row.get("apply_date") or "")[:10], "%Y-%m-%d").date()
    except ValueError:
        return False
    return span[0] <= day <= span[1]


def _span_label(span: tuple) -> str:
    start, end = (display_date(d.isoformat()) for d in span)
    return f"for {start}" if span[0] == span[1] else f"from {start} to {end}"


def _status_sentence(row: dict, whose: str = "Your") -> str:
    """One request answered directly: "Your regularization request REG-131
    for 29-Sep-2026 (Missed punch-out, 9:30 AM to 6:30 PM) is Pending
    approval." - plus the rejection / cancel reason when erp-api sent one."""
    ref = row.get("reference_id") or f"REG-{row.get('regularization_id')}"
    when = row.get("apply_date_display") or row.get("apply_date") or "-"
    times = " to ".join(t for t in (row.get("in_time_display"), row.get("out_time_display")) if t)
    details = ", ".join(d for d in (row.get("regularization_type"), times) if d)
    status = row.get("card_status_label") or row.get("status_label") or row.get("status_name") or "-"
    sentence = (f"{whose} regularization request {ref} for {when}"
                f"{f' ({details})' if details else ''} is {status}.")
    for key, label in (("rejection_reason", "Rejection reason"), ("cancel_reason", "Cancel reason")):
        if str(row.get(key) or "").strip():
            sentence += f" {label}: {str(row[key]).strip()}."
    return sentence


async def _team_request_by_reference(state: dict, reference: int) -> Optional[dict]:
    """A Manager/HR/Admin asking about a REG that isn't their own may mean a
    team member's - only the pending team queue is readable, so that is
    where it is looked for. None when not found or not allowed."""
    if not permission_service.routes_as_manager(state):
        return None
    try:
        result = await erp_client.get_pending_regularizations(
            state.get("bearer_token"), company_id=state.get("company_id"),
            conversation_id=state.get("conversation_id", ""))
    except Exception:
        return None
    rows = ((result.get("body") or {}).get("data") or {}).get("regularizations") or []
    match = next((r for r in rows if str(r.get("regularization_id")) == str(reference)), None)
    return enrich_rows([match])[0] if match else None


async def my_regularisation_view_node(state: dict, writer: StreamWriter) -> dict:
    company_id = state.get("company_id")
    conversation_id = state.get("conversation_id", "")
    bearer_token = state.get("bearer_token")
    usage_events = list(state.get("usage_events", []))

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

    status_filter = _requested_status_filter(state.get("query") or "")

    writer({"type": "fetching_my_regularizations",
            "message": "Checking your regularization requests..."})

    try:
        result = await erp_client.get_my_regularizations(
            bearer_token, company_id=company_id, conversation_id=conversation_id,
            status=status_filter,
        )
    except erp_client.ErpApiTimeout:
        return _finish(ERP_TIMEOUT_MESSAGE)
    except erp_client.ErpApiUnavailable:
        return _finish(ERP_UNAVAILABLE_MESSAGE)

    body = result.get("body") or {}

    # erp-api refusing the FILTER value itself. Live: status=cancelled came
    # back {"message": "The selected status is invalid."}, which reached the
    # employee as the answer to "show my cancelled regularization". The rows
    # carry status_name, and the filter is applied to them below anyway, so
    # an unfiltered list filtered here gives the same answer — erp-api's
    # validation message is for this code, not for the employee.
    filtered_here = False
    if status_filter and (not body.get("success", True)
                          or (result.get("http_status") or 200) >= 400):
        logger.warning("[MyRegularisations] erp-api refused status=%s (%s) - "
                       "fetching all and filtering here",
                       status_filter, body.get("message"))
        try:
            result = await erp_client.get_my_regularizations(
                bearer_token, company_id=company_id, conversation_id=conversation_id,
            )
        except erp_client.ErpApiTimeout:
            return _finish(ERP_TIMEOUT_MESSAGE)
        except erp_client.ErpApiUnavailable:
            return _finish(ERP_UNAVAILABLE_MESSAGE)
        body = result.get("body") or {}
        filtered_here = True

    if not body.get("success", True):
        # erp-api answering, not failing - its own wording is the honest reply.
        return _finish(str(body.get("message") or NONE_FOUND_MESSAGE))

    data = body.get("data") or {}
    # Type, Ref ID, Applied by/on and the Figma date format ride on each row
    # (regularisation_display.enrich_row); erp-api's own keys are unchanged.
    rows = enrich_rows(_newest_first(data.get("regularizations") or []))
    # erp-api filters by ?status= itself; this only guarantees "show my
    # pending regularizations" never lists a cancelled row even if a
    # deployment ignored the parameter.
    if status_filter:
        wanted = _FILTER_STATUSES.get(status_filter, (status_filter,))
        rows = [r for r in rows if status_key(r) in wanted]

    # Narrowed to ONE request by reference ("status of REG-131"), or to a day
    # or span ("my regularization for 29 sept", "rejected ones in september").
    # QA: these were listed in full - the date and the reference were ignored.
    query = state.get("query") or ""
    reference = _requested_reference(query)
    span = None if reference is not None else _requested_dates(query, _today())
    if reference is not None:
        rows = [r for r in rows if str(r.get("regularization_id")) == str(reference)]
    elif span:
        rows = [r for r in rows if _in_dates(r, span)]
    narrowed = reference is not None or span is not None
    filters = {"reference_filter": f"REG-{reference}" if reference is not None else None,
               "date_filter": ({"from": span[0].isoformat(), "to": span[1].isoformat()}
                               if span else None)}
    # Row buttons: Cancel while Pending (cancel=true), never approve/reject on
    # the employee's own requests - see regularisation_display.employee_actions.
    rows = [{**r, **employee_actions(r)} for r in rows]
    # What this reply shows, so a following "cancel this" means these
    # requests (regularisation_cancel.LAST_VIEW_NAMESPACE).
    slot_store.set_slots("regularization_last_view", company_id, conversation_id,
                         {"ids": [r.get("regularization_id") for r in rows]})

    # erp-api's own counts, passed through as given - they follow the status
    # filter (see erp_client.get_my_regularizations), so they are never
    # recomputed from the rows here.
    counts = {
        key: data.get(key)
        for key in (
            "total_regularizations",
            "total_pending_regularizations",
            "total_approved_regularizations",
            "total_rejected_regularizations",
            "total_cancelled_regularizations",
        )
    }
    if counts["total_regularizations"] is None:
        counts["total_regularizations"] = len(rows)
    if filtered_here or narrowed:
        # The counts came back for a wider list; the total has to describe
        # the filtered list shown, the way a real ?status= answer's does.
        counts["total_regularizations"] = len(rows)

    if not rows:
        if reference is not None:
            # Not one of the caller's own - for a Manager/HR/Admin it may be a
            # team member's pending request.
            team_row = await _team_request_by_reference(state, reference)
            if team_row is not None:
                who = team_row.get("employee_name") or "Your team member"
                return _finish(_status_sentence(team_row, whose=f"{who}'s"), extra_data={
                    "regularizations": [team_row], "total_count": 1, **filters,
                    "status_filter": status_filter, "found": True, "team_request": True})
            message = f"I couldn't find REG-{reference} among your regularization requests."
        elif span is not None:
            qualifier = f"{status_filter} " if status_filter else ""
            message = f"You don't have any {qualifier}regularization requests {_span_label(span)}."
        else:
            message = (f"You don't have any {status_filter} regularization requests."
                       if status_filter else NONE_FOUND_MESSAGE)
        # The empty state is an ANSWER, and it carries the empty list so a UI
        # can render its own "nothing found" card rather than re-deriving the
        # fact from the sentence.
        return _finish(message, extra_data={
            "regularizations": [],
            "total_count": 0,
            **{k: (v or 0) for k, v in counts.items()},
            **filters,
            "status_filter": status_filter,
            "found": False,
        })

    # One request asked about - by reference, by its date, or as a yes/no
    # question - is answered directly rather than as a one-row table.
    folded = fold_regularization_typos(fold_smart_punctuation(query.lower()))
    if reference is not None or (len(rows) == 1 and (span is not None
                                                     or _YES_NO_QUESTION_RE.search(folded)
                                                     or "status" in folded)):
        message = _status_sentence(rows[0])
    else:
        message = _render_list(rows, status_filter, _span_label(span) if span else None)

    return _finish(message, extra_data={
        "regularizations": rows,
        # How many requests the table holds (after any filter) - the count the
        # frontend shows on the regularization table.
        "total_count": len(rows),
        **counts,
        **filters,
        "status_filter": status_filter,
        "has_more": len(rows) > _LIST_LIMIT,
        "found": True,
    })
