import json
import logging
import re
from datetime import date, datetime, timedelta

from schema.agent import HRState
from langgraph.types import StreamWriter

from services import erp_client as attendance_client
from services import slot_store
from services.slot_flow import SlotFlowConfig, run_slot_flow, _build_entry_cards
from dataclasses import replace
# Reused for its deterministic explicit-date regexes/resolver (numeric
# DD/MM(/YYYY) and day+named-month) — see _build_detected_dates_block
# below. Aliased rather than importing individual names since several of
# these are regex objects rather than functions.
import services.attendance as attendance_mod

logger = logging.getLogger(__name__)


ENTRY_FIELDS = ["date", "start_time", "end_time", "reason"]

ENTRY_FIELD_LABELS = {
    "date": "the date",
    "start_time": "the start (in) time",
    "end_time": "the end (out) time",
    "reason": "the reason for regularization",
}

_MULTISESSION_STATUS = "multisession"
_COMPLETE_STATUS = "complete"

_EXCEPTION_LABELS = {
    "missing_checkin": "Missing Check-in",
    "missing_checkout": "Missing Check-out",
    "no_punch": "No Punch Recorded",
}

# Explicit cancel language only — short neutral acknowledgments like "ok"
# must NOT match this, or a bare "ok" sent while fields are still missing
# gets treated as abandoning the request (observed bug). "not now" is a
# safe substring add — it's specific enough that it won't appear inside a
# genuine reason/time answer by accident, same reasoning as "cancel"/
# "withdraw" above.
_EXPLICIT_CANCEL_PATTERN = re.compile(
    r"\b(cancel|never\s*mind|forget\s*it|withdraw|drop\s*it|not\s+now|"
    r"don'?t\s*(bother|submit|do\s*it)|stop\s*(this|it)?)\b",
    re.IGNORECASE,
)

# A bare decline ("no", "nope", "nah") only counts as an explicit cancel
# when it IS essentially the whole message — unlike "cancel"/"not now"
# above, "no" is a common word that can legitimately open a genuine
# reason/time answer while a field is still pending (e.g. "no particular
# reason, just forgot to punch out") — matching it as a substring there
# would wrongly abandon an in-progress answer instead of recording it.
# Anchoring to (almost) the entire message keeps the two apart: a bare
# "no"/"nope" reply matches, "no particular reason..." does not.
_BARE_DECLINE_PATTERN = re.compile(r"^\s*(no|nope|nah)\s*[.!]*\s*$", re.IGNORECASE)


def _is_explicit_cancel(query: str) -> bool:
    return bool(_EXPLICIT_CANCEL_PATTERN.search(query)) or bool(_BARE_DECLINE_PATTERN.match(query))


def _display_date(iso_date: str) -> str:
    try:
        return datetime.strptime(iso_date, "%Y-%m-%d").strftime("%d %b %Y")
    except (ValueError, TypeError):
        return iso_date


# ---------------------------------------------------------------------------
# Multi-entry summary / success formatters
# ---------------------------------------------------------------------------

def _format_multi_summary(entries: list[dict]) -> str:
    lines = [
        f"- **{_display_date(e['date'])}:** {e.get('start_time')}–"
        f"{e.get('end_time')}, reason: {e.get('reason')}"
        for e in entries
    ]

    plural = "s" if len(entries) > 1 else ""

    return (
        f"Here's the regularization request{plural} I'll submit:\n\n"
        + "\n".join(lines)
        + f"\n\nShall I go ahead and submit {'these' if len(entries) > 1 else 'this'}?"
    )


def _format_multi_success(entries: list[dict], results: list[dict]) -> str:
    lines = []

    for entry, result in zip(entries, results):
        status = "submitted" if result["ok"] else f"failed — {result['error']}"
        lines.append(f"- {_display_date(entry['date'])}: {status}")

    ok_count = sum(r["ok"] for r in results)

    if ok_count == len(results):
        header = "All your regularization requests were submitted successfully:"
    elif ok_count == 0:
        header = "Sorry, I wasn't able to submit any of your regularization requests:"
    else:
        header = "Some of your regularization requests were submitted:"

    return header + "\n\n" + "\n".join(lines)


def _extract_failure_message(entry: dict, body: dict):
    """Pulls a human-readable message out of the ERP's 400 body for a
    single entry. Sync is fine here (no LLM call needed) — kept as a
    plain function so inspect.isawaitable(...) is False and slot_flow.py
    uses the return value directly."""
    return (
        body.get("message")
        or body.get("msg")
        or body.get("error")
        or body.get("detail")
    )


# ---------------------------------------------------------------------------
# Punch/shift pre-fill
# ---------------------------------------------------------------------------

def _extract_punch_datetime(value: str | None) -> datetime | None:
    if not value:
        return None
    value = value.strip()
    try:
        return datetime.strptime(value, "%Y-%m-%d %H:%M:%S")
    except ValueError:
        return None


def _format_punch_display(dt: datetime | None, requested_date: str) -> str | None:
    if not dt:
        return None
    label = dt.strftime("%H:%M")
    try:
        req = datetime.strptime(requested_date, "%Y-%m-%d").date()
        if dt.date() != req:
            label += " (next day)" if dt.date() > req else " (prev day)"
    except (ValueError, TypeError):
        pass
    return label


def _session_display(session: dict, date_iso: str) -> dict:
    check_in_dt = _extract_punch_datetime(session.get("check_in"))
    check_out_dt = _extract_punch_datetime(session.get("check_out"))
    return {
        "check_in": _format_punch_display(check_in_dt, date_iso),
        "check_out": _format_punch_display(check_out_dt, date_iso),
        "complete": bool(session.get("complete")),
    }


def _resolve_exception(punch_status: str | None, punches: list[dict]) -> str:
    # If the API provided a punch_status, use it directly (formatted to title case)
    if punch_status:
        if punch_status.lower() in (_COMPLETE_STATUS, "complete"):
            return "None"
        return punch_status.replace("_", " ").title()

    # Fallback logic if punch_status is missing from API response
    if not punches:
        return "No Punch Recorded"

    has_check_in = any(p.get("check_in") for p in punches)
    has_check_out = any(p.get("check_out") for p in punches)

    if has_check_in and not has_check_out:
        return "Missing Check-out"
    if has_check_out and not has_check_in:
        return "Missing Check-in"
    if not has_check_in and not has_check_out:
        return "No Punch Recorded"

    return "None"


async def _get_attendance_prefill(
    *, bearer_token, date_iso: str, company_id, conversation_id, writer: StreamWriter, employee_name: str | None = None
) -> dict:
    empty_preview = {
        "date": date_iso, "shift": None, "lms_punch": [],
        "biometric": None, "exception": "No Punch Recorded", "punch_status": None,
    }

    try:
        writer({"type": "fetching_punch_time", "message": "Checking your punch-in and punch-out times..."})

        result = await attendance_client.get_punch_time(
            bearer_token, company_id=company_id, conversation_id=conversation_id, date=date_iso,
            employee_name=employee_name,
        )

        # Safely unwrap response whether nested inside 'body' or top-level dict
        body = result.get("body") if isinstance(result, dict) and "body" in result else result
        if not isinstance(body, dict) or not body.get("success", True):
            logger.warning("[Graph] punch details API returned failure: %s", result)
            return {"slot_prefill": {}, "preview": empty_preview}

        data = body.get("data") or {}
        punches = data.get("punches") or data.get("sessions") or []
        shift = data.get("shift")
        punch_status = data.get("punch_status")

        exception = _resolve_exception(punch_status, punches)

        # Case-insensitive: _resolve_exception above already lowercases when
        # deciding the "None" label, so an exact-case comparison here could
        # show the user "exception: None" (implying nothing to worry about)
        # while silently NOT auto-filling anything if erp-api ever returns
        # punch_status as "Complete" or another case variant — confirmed
        # live, a real mismatch between the two checks.
        is_complete = bool(punch_status) and punch_status.lower() == _COMPLETE_STATUS

        if is_complete and len(punches) > 1:
            # Multiple complete sessions (split shift) — erp-api's status is
            # genuinely "complete" so the plain exception label would read
            # "None", but auto-fill (below) can't populate a single
            # start/end pair from more than one session. Make that explicit
            # instead of leaving the user to wonder why nothing got filled
            # in on an apparently-fine day.
            exception = "Multiple Sessions — review times manually"

        preview = {
            "date": date_iso,
            "shift": {
                "name": shift.get("name"),
                "start_time": shift.get("start_time"),
                "end_time": shift.get("end_time"),
            } if shift else None,
            "lms_punch": [_session_display(p, date_iso) for p in punches],
            "biometric": None,
            "exception": exception,
            "punch_status": punch_status,
        }

        slot_prefill = {}
        if is_complete and len(punches) == 1:
            p = punches[0]
            check_in_dt = _extract_punch_datetime(p.get("check_in"))
            check_out_dt = _extract_punch_datetime(p.get("check_out"))
            if check_in_dt:
                slot_prefill["start_time"] = check_in_dt.strftime("%H:%M")
            if check_out_dt:
                slot_prefill["end_time"] = check_out_dt.strftime("%H:%M")

        logger.info(
            "[Graph] attendance prefill for %s: punch_status=%s punches=%d slot_prefill=%s",
            date_iso, punch_status, len(punches), slot_prefill,
        )

        return {"slot_prefill": slot_prefill, "preview": preview}

    except attendance_client.ErpApiTimeout:
        logger.warning("[Graph] punch details timeout for %s", date_iso)
        writer({"type": "punch_time_warning",
                "message": "I couldn't retrieve your punch times. I'll ask you for them instead."})
        return {"slot_prefill": {}, "preview": empty_preview}

    # ErpApiUnauthorized is a SUBCLASS of ErpApiUnavailable (see
    # erp_client.py) — must be caught first, or the general clause below
    # silently swallows every 401 into the wrong message.
    except attendance_client.ErpApiUnauthorized:
        logger.warning("[Graph] punch details request unauthorized for %s", date_iso)
        writer({"type": "punch_time_warning",
                "message": "I couldn't verify your session for punch details. I'll ask you for the times instead."})
        return {"slot_prefill": {}, "preview": empty_preview}

    except attendance_client.ErpApiUnavailable:
        logger.warning("[Graph] punch details unavailable for %s", date_iso)
        writer({"type": "punch_time_warning",
                "message": "I couldn't reach the HR system for your punch details, so I'll just ask you for the times instead."})
        return {"slot_prefill": {}, "preview": empty_preview}

    except Exception as e:
        logger.exception("[Graph] unexpected punch details error for %s: %s", date_iso, e)
        return {"slot_prefill": {}, "preview": empty_preview}


# ---------------------------------------------------------------------------
# Submit
# ---------------------------------------------------------------------------

async def _submit(merged: dict, *, bearer_token, company_id, conversation_id) -> dict:
    payload = {
        "apply_date": merged["date"],
        "from_time": merged["start_time"],
        "to_time": merged["end_time"],
        "reason": merged["reason"],
    }
    if merged.get("employee_name"):
        payload["employee_name"] = merged["employee_name"]

    return await attendance_client.post_regularization(
        bearer_token, payload=payload, company_id=company_id, conversation_id=conversation_id,
    )


def _map_exception(exc: Exception):
    if isinstance(exc, attendance_client.ErpApiTimeout):
        return "I couldn't reach the HR system in time — please try again in a moment."
    # ErpApiUnauthorized is a SUBCLASS of ErpApiUnavailable (see
    # erp_client.py) — must be checked first, or the isinstance check below
    # matches it too and returns the wrong message.
    if isinstance(exc, attendance_client.ErpApiUnauthorized):
        return "Sorry, your session has expired — please log in again to continue."
    if isinstance(exc, attendance_client.ErpApiUnavailable):
        return "I'm unable to reach the HR system right now — please try again shortly."
    return None


# ---------------------------------------------------------------------------
# Prompt
# ---------------------------------------------------------------------------

def _build_day_of_week_table(today: date, days_back: int = 21, days_forward: int = 7) -> str:
    """A literal date -> weekday-name lookup table for the surrounding ~4
    weeks, injected into the prompt so the LLM can LOOK UP which date a
    weekday name means instead of computing it — confirmed live and
    repeatedly wrong when left to compute it itself (e.g. "Monday and
    Tuesday" resolved to a Saturday and a Sunday; "last week Monday"
    resolved to a date two weeks out that wasn't even a Monday). This
    codebase already learned this lesson elsewhere (see
    attendance_explain.py's deterministic weekday resolver) — this prompt
    is the one place date math was still being left to the model itself."""
    lines = []
    for offset in range(-days_back, days_forward + 1):
        d = today + timedelta(days=offset)
        tag = " <- TODAY" if offset == 0 else ""
        lines.append(f"{d.isoformat()} {d.strftime('%A')}{tag}")
    return "\n".join(lines)


def _build_detected_dates_block(query: str, today: date) -> str:
    """Deterministically pre-resolves any explicit numeric (DD/MM(/YYYY))
    or day+named-month date(s) mentioned in the CURRENT message — the same
    closed, unambiguous shape attendance.py's own deterministic layer
    resolves for the plain attendance/attendance_explain/punch_details
    flows — and hands the LLM the already-computed ISO date(s) to use
    verbatim. Same "look it up, don't compute" approach as the
    DAY-OF-WEEK REFERENCE TABLE above (see its docstring): without this,
    the LLM has to get day-first-not-month-first and current-year-when-
    absent right on its own every time, and this family of date-extraction
    prompts has repeatedly shown that's not reliable (observed bug: a
    year-less explicit date silently defaulting to today's date)."""
    seen = set()
    resolved_pairs = []

    for m in attendance_mod._ATTENDANCE_EXPLICIT_NUMERIC_DATE_RE.finditer(query):
        resolved = attendance_mod._resolve_explicit_date_symbolic(
            int(m.group(1)), int(m.group(2)), m.group(3), today,
        )
        if resolved and m.group(0) not in seen:
            seen.add(m.group(0))
            resolved_pairs.append((m.group(0), resolved["explicit_date"]))

    for pattern in (
        attendance_mod._ATTENDANCE_DAY_THEN_MONTH_RE,
        attendance_mod._ATTENDANCE_MONTH_THEN_DAY_RE,
    ):
        for m in pattern.finditer(query):
            if m.group(0) in seen:
                continue
            g1, g2, year_str = m.group(1), m.group(2), m.group(3)
            if g1.isdigit():
                day, month_word = int(g1), g2.lower()
            else:
                month_word, day = g1.lower(), int(g2)
            month = attendance_mod._MONTH_NAMES.get(month_word)
            if not month:
                continue
            resolved = attendance_mod._resolve_explicit_date_symbolic(day, month, year_str, today)
            if resolved:
                seen.add(m.group(0))
                resolved_pairs.append((m.group(0), resolved["explicit_date"]))

    if not resolved_pairs:
        return ""

    lines = "\n".join(f'- "{text}" -> {iso}' for text, iso in resolved_pairs)
    return f"""
The following date(s) mentioned in the CURRENT message have ALREADY been
resolved (day-first, current year assumed if none was stated) — use these
EXACT ISO values verbatim for that date, do NOT recompute or reinterpret
them:
{lines}
"""


def _build_prompt(
    query: str,
    existing_slots: dict,
    today: date,
    candidate_dates: list[str] | None = None,
) -> str:

    today_str = today.strftime("%Y-%m-%d")
    today_day = today.strftime("%A")
    day_of_week_table = _build_day_of_week_table(today)
    detected_dates_block = _build_detected_dates_block(query, today)

    existing_entries = existing_slots.get("entries") or []

    existing_str = (
        "\n".join(
            f"- date={e.get('date')}, start_time={e.get('start_time')}, "
            f"end_time={e.get('end_time')}, reason={e.get('reason')}"
            for e in existing_entries
        )
        or "none yet"
    )

    candidates_block = ""
    if candidate_dates:
        candidates_str = ", ".join(candidate_dates)
        candidates_block = f"""
The employee was previously offered a choice between these candidate
dates (none confirmed yet): {candidates_str}
If the message names one of these dates (or a day name that clearly
matches one of them), treat it as selecting that date for a new entry.
"""

    return f"""You are helping fill out one or more attendance regularization
requests through a multi-turn conversation. Today's date is {today_str}
({today_day}).

DAY-OF-WEEK REFERENCE TABLE — use this to find which date a weekday name
means. Do NOT calculate it yourself; look it up here:
{day_of_week_table}
{detected_dates_block}
Entries already collected so far (one per date):
{existing_str}
{candidates_block}
Some start_time/end_time values may have been automatically retrieved from
the employee's attendance punch records — treat those as valid collected
values already present above.

Read the employee's latest message and output ONLY a JSON object:

{{
  "action": "provide_info" | "confirm" | "cancel",
  "entries": [
    {{
      "date": "YYYY-MM-DD" or null,
      "start_time": "HH:MM" or null,
      "end_time": "HH:MM" or null,
      "reason": "<short reason text>" or null
    }}
  ],
  "employee_name": "<name>" or null
}}

Rules:

- If the message mentions MULTIPLE dates (e.g. "Monday and Tuesday"),
  output ONE entry per date, each resolved to an absolute YYYY-MM-DD
  against {today_str}.
- Only include an entry in "entries" for a date if THIS message mentions
  or changes something for that date (a new date, a time, or a reason).
  Do NOT repeat entries from "already collected" that this message
  doesn't touch.
- If the message gives one reason but multiple dates, apply that same
  reason to every new entry for those dates.
- If the message gives one time range but multiple dates, apply it to
  every new entry for those dates, unless different times are given per
  date.
- If the employee explicitly provides a different start or end time for
  a date that's already collected, output an entry with that date and
  the new value(s) — the flow will overwrite the previous value for that
  date. Explicit values always take precedence over automatically
  retrieved punch values.
- If the message provides ONLY time(s) and/or a reason, with NO date
  mentioned or implied anywhere in the message, you MUST still output
  exactly one entry for it, with "date": null. This applies equally
  whether the message gives a time, a reason, or both — never omit the
  entry entirely just because there's no date. Do NOT guess which
  existing entry it belongs to — that is handled outside this prompt.
- NEVER default an unmentioned date to today's date ({today_str}) just
  because no date was given. Only use {today_str} as an entry's date if
  the employee's message actually says "today" or otherwise clearly
  refers to the current date.
- "cancel" ONLY if the message explicitly asks to stop/abandon/withdraw
  the request — e.g. "cancel", "never mind", "forget it", "stop", "don't
  bother", "no don't submit it", "not now", or a bare "no"/"nope"/"nah"
  declining the request. A short acknowledgment like "ok", "okay",
  "alright", "fine", "sure", "got it" is NEVER a cancel — treat it as
  "provide_info" with empty entries (the employee is just acknowledging,
  not answering or cancelling).
- "confirm" ONLY if the message is a clear affirmative meant to submit
  the request as currently collected (e.g. "yes submit it", "go ahead",
  "confirm").
- If the message contains no new date/time/reason information AND is
  not a clear confirm or explicit cancel, use "provide_info" with
  "entries": [] — do not guess.
- Resolve relative dates (today/yesterday/Monday/Tuesday/last week's
  Wednesday/etc.) using the DAY-OF-WEEK REFERENCE TABLE above — look the
  date up, do not compute it.
- Any slash- or dash-separated numeric date (e.g. "10/08/2026",
  "05-03-2026") is DD/MM/YYYY (day first), NEVER MM/DD/YYYY — this
  applies even when both numbers are <= 12 and the format looks
  ambiguous. Do NOT default to US month-first convention.
  - "10/08/2026" -> "2026-08-10" (10th of August, NOT October 8th)
  - "05-03-2026" -> "2026-03-05" (5th of March, NOT May 3rd)
- A date with NO year stated — either numeric ("12-08", "21/07") or a
  named-month day ("23 aug", "12 August") — is still DD/MM (day first for
  the numeric form) and uses {today_str}'s year ({today.year}), never left
  null and never defaulted to today's date:
  - "12-08" -> "{today.year}-08-12" (12th of August THIS year)
  - "23 aug" -> "{today.year}-08-23" (23rd of August THIS year)
- Times must be returned in 24-hour HH:MM format.
- employee_name should only be set if another employee is explicitly
  named. For the employee's own attendance, employee_name must be null.
- reason should be a short paraphrase.

Examples:

Existing:
- date=2026-08-15, start_time=09:10, end_time=18:05, reason=None

Message:
"I forgot to punch out"

Output:
{{"action":"provide_info","entries":[{{"date":"2026-08-15","start_time":null,"end_time":null,"reason":"forgot to punch out"}}],"employee_name":null}}

Existing:
none yet

Message (illustrative — if today were 2026-08-27, a Thursday, so the table
would show 2026-08-24=Monday and 2026-08-25=Tuesday):
"Regularize my missing punch for Monday and Tuesday"

Output — each weekday name resolved by LOOKING IT UP in the reference
table above, never by computing it:
{{"action":"provide_info","entries":[
  {{"date":"2026-08-24","start_time":null,"end_time":null,"reason":"missing punch"}},
  {{"date":"2026-08-25","start_time":null,"end_time":null,"reason":"missing punch"}}
],"employee_name":null}}

Existing:
- date=2026-08-15, start_time=09:10, end_time=18:05, reason=forgot to punch out

Message:
"change the end time to 7pm"

Output:
{{"action":"provide_info","entries":[{{"date":"2026-08-15","start_time":null,"end_time":"19:00","reason":null}}],"employee_name":null}}

Existing:
- date=2026-08-15, start_time=09:10, end_time=18:05, reason=forgot to punch out

Message:
"yes go ahead"

Output:
{{"action":"confirm","entries":[],"employee_name":null}}

Existing:
- date=2026-07-30, start_time=None, end_time=None, reason=None

Message:
"ok"

Output:
{{"action":"provide_info","entries":[],"employee_name":null}}

Existing:
- date=2026-07-31, start_time=None, end_time=None, reason=None

Message:
"10 se 7 bje mujhe late hua tha"

Output (no date mentioned in the message — leave date null, do NOT use {today_str}):
{{"action":"provide_info","entries":[{{"date":null,"start_time":"10:00","end_time":"19:00","reason":"was late"}}],"employee_name":null}}

Existing:
none yet

Message (illustrative — today's year is {today.year}):
"regularize my attendance for 23 aug"

Output — day+month with no year stated, resolved to THIS year, never left null:
{{"action":"provide_info","entries":[{{"date":"{today.year}-08-23","start_time":null,"end_time":null,"reason":"regularization request"}}],"employee_name":null}}

Current message:
{query}
"""


# ---------------------------------------------------------------------------
# Config
# ---------------------------------------------------------------------------

REGULARIZATION_CONFIG = SlotFlowConfig(
    name="regularization",
    required_fields=[],
    field_labels={},
    build_prompt=_build_prompt,
    submit=_submit,
    map_submit_exception=_map_exception,
    extract_failure_message=_extract_failure_message,
    entry_fields=ENTRY_FIELDS,
    entry_field_labels=ENTRY_FIELD_LABELS,
    entry_key="date",
    format_multi_summary=_format_multi_summary,
    format_multi_success=_format_multi_success,
    is_explicit_cancel=_is_explicit_cancel,
)


# ---------------------------------------------------------------------------
# Structured edit support (Save button — bypasses the LLM entirely)
# ---------------------------------------------------------------------------
#
# Expected structured query shape (state["query"] is JSON text):
#   {"action": "edit_entry", "date": "2026-07-30",
#    "start_time": "10:00", "end_time": "19:00", "reason": "..."}
#   {"action": "remove_entry", "date": "2026-07-30"}
#
# Any field omitted/null is left unchanged. Any other query shape (plain
# string, or JSON without a recognized "action") falls through to the
# normal LLM-driven flow untouched.

_STRUCTURED_ACTIONS = {"edit_entry", "remove_entry"}


def _try_parse_structured_action(query: str) -> dict | None:
    try:
        parsed = json.loads(query)
    except (json.JSONDecodeError, TypeError):
        return None

    if not isinstance(parsed, dict):
        return None

    if parsed.get("action") not in _STRUCTURED_ACTIONS:
        return None

    return parsed


async def _handle_structured_action(
    payload: dict,
    *,
    company_id,
    conversation_id: str,
    writer: StreamWriter,
    usage_events: list,
) -> dict:

    stored = slot_store.get_slots("regularization", company_id, conversation_id) or {}
    entries = stored.get("entries") or []
    employee_name = stored.get("employee_name")

    date_iso = payload.get("date")
    if not date_iso:
        message = "I need a date to know which entry to update."
        writer({"type": "done", "intent": "regularization_incomplete", "is_hr": True,
                "data": {"answer": message}, "message": message, "usage_events": usage_events})
        return {"response_text": message, "usage_events": usage_events}

    if payload["action"] == "remove_entry":
        entries = [e for e in entries if e.get("date") != date_iso]
    else:  # edit_entry
        updates = {
            k: payload.get(k)
            for k in ("start_time", "end_time", "reason")
            if payload.get(k) is not None
        }
        found = False
        for e in entries:
            if e.get("date") == date_iso:
                e.update(updates)
                found = True
                break
        if not found:
            entries.append({"date": date_iso, **updates})

    slot_store.set_slots(
        "regularization", company_id, conversation_id,
        {"entries": entries, "employee_name": employee_name},
    )

    def _missing_for(entry):
        return [f for f in ENTRY_FIELDS if not entry.get(f)]

    entries_missing = any(_missing_for(e) for e in entries)
    status = "incomplete" if (not entries or entries_missing) else "awaiting_confirmation"

    writer({
        "type": "regularization_card",
        "data": _build_entry_cards(REGULARIZATION_CONFIG, entries, status),
    })

    if not entries:
        message = "Done — I've removed that entry."
    elif entries_missing:
        message = "Updated — a few details are still missing before I can submit."
    else:
        message = _format_multi_summary(entries)

    data = {"answer": message}
    if status == "awaiting_confirmation":
        data["is_conceled"] = False

    writer({"type": "done", "intent": f"regularization_{status}", "is_hr": True,
            "data": data, "message": message, "usage_events": usage_events})

    return {"response_text": message, "usage_events": usage_events}


# ---------------------------------------------------------------------------
# Node
# ---------------------------------------------------------------------------

async def regularisation_node(
    state: HRState,
    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", []))

    punch_previews: dict[str, dict] = {}

    # ================================================================
    # Safe writer
    # ================================================================

    def wrapped_writer(event: dict):
        try:
            if isinstance(event, dict) and event.get("type") == "done":
                stored_slots = (
                    slot_store.get_slots(
                        "regularization",
                        company_id,
                        conversation_id,
                    )
                    or {}
                )

                current_entries = (
                    stored_slots.get("entries")
                    or []
                )

                data = event.get("data")

                if not isinstance(data, dict):
                    data = {}

                data["filled_details"] = current_entries

                data["punch_details"] = (
                    punch_previews.get(
                        current_entries[0]["date"]
                    )
                    if (
                        len(current_entries) == 1
                        and current_entries[0].get("date")
                        in punch_previews
                    )
                    else punch_previews
                )

                event["data"] = data

            writer(event)

        except Exception:
            # Never expose writer/enrichment errors to frontend
            logger.exception(
                "[Graph] Failed to process regularisation writer event"
            )

            # Try sending a safe error event
            try:
                writer({
                    "type": "done",
                    "intent": "regularization_error",
                    "is_hr": True,
                    "data": {
                        "answer": (
                            "I couldn't complete your regularization request right now — please try again in a moment."
                        ),
                        "node_type": "error",
                    },
                    "message": (
                        "I couldn't complete your regularization request right now — please try again in a moment."
                    ),
                    "usage_events": usage_events,
                })
            except Exception:
                logger.exception(
                    "[Graph] Failed to send regularisation writer error"
                )

    # ================================================================
    # Prefill fetch
    # ================================================================

    async def _fetch_prefill(
        entry: dict,
        w: StreamWriter,
    ) -> dict:

        try:
            date_iso = entry.get("date")

            if not date_iso:
                return {}

            attendance = await _get_attendance_prefill(
                bearer_token=bearer_token,
                date_iso=date_iso,
                company_id=company_id,
                conversation_id=conversation_id,
                writer=w,
            )

            punch_previews[date_iso] = attendance["preview"]

            w({
                "type": "regularization_prefill_preview",
                "data": attendance["preview"],
            })

            return attendance["slot_prefill"]

        except Exception:
            logger.exception(
                "[Graph] Failed to fetch regularisation prefill "
                "for date=%s",
                entry.get("date") if isinstance(entry, dict) else None,
            )

            # Do not expose internal exception details
            try:
                w({
                    "type": "regularization_prefill_error",
                    "message": (
                        "I couldn't fetch the attendance details "
                        "for this date. Please try again."
                    ),
                })
            except Exception:
                logger.exception(
                    "[Graph] Failed to send prefill error event"
                )

            # Returning {} allows slot flow to continue without
            # exposing the underlying exception.
            return {}

    # ================================================================
    # Main node
    # ================================================================

    try:

        # ------------------------------------------------------------
        # Structured action
        # ------------------------------------------------------------

        structured = _try_parse_structured_action(
            state["query"]
        )

        if structured:
            try:
                return await _handle_structured_action(
                    structured,
                    company_id=company_id,
                    conversation_id=conversation_id,
                    writer=wrapped_writer,
                    usage_events=usage_events,
                )

            except Exception:
                logger.exception(
                    "[Graph] Structured regularisation action failed"
                )

                error_message = (
                    "I couldn't process your regularization request right now — please try again in a moment."
                )

                try:
                    writer({
                        "type": "done",
                        "intent": "regularization_error",
                        "is_hr": True,
                        "data": {
                            "answer": error_message,
                            "node_type": "error",
                        },
                        "message": error_message,
                        "usage_events": usage_events,
                    })
                except Exception:
                    logger.exception(
                        "[Graph] Failed to send structured "
                        "regularisation error"
                    )

                return {
                    "response_text": error_message,
                    "usage_events": usage_events,
                }

        # ------------------------------------------------------------
        # Configure slot flow with prefill callback
        # ------------------------------------------------------------

        config = replace(
            REGULARIZATION_CONFIG,
            fetch_entry_prefill=_fetch_prefill,
        )

        # ------------------------------------------------------------
        # Load stored regularisation slots
        # ------------------------------------------------------------

        try:
            stored = (
                slot_store.get_slots(
                    "regularization",
                    company_id,
                    conversation_id,
                )
                or {}
            )

            candidate_dates = stored.get(
                "candidate_dates"
            )

        except Exception:
            logger.exception(
                "[Graph] Failed to load regularisation slots"
            )

            candidate_dates = None

        # ------------------------------------------------------------
        # Run slot flow
        # ------------------------------------------------------------

        try:
            result = await run_slot_flow(
                config,
                state,
                wrapped_writer,
                candidate_dates=candidate_dates,
            )

            return result

        except Exception:
            logger.exception(
                "[Graph] Regularisation slot flow failed"
            )

            error_message = (
                "I couldn't process your regularization request right now — please try again in a moment."
            )

            try:
                writer({
                    "type": "done",
                    "intent": "regularization_error",
                    "is_hr": True,
                    "data": {
                        "answer": error_message,
                        "node_type": "error",
                    },
                    "message": error_message,
                    "usage_events": usage_events,
                })

            except Exception:
                logger.exception(
                    "[Graph] Failed to send regularisation "
                    "slot-flow error"
                )

            return {
                "response_text": error_message,
                "usage_events": usage_events,
            }

    # ================================================================
    # GLOBAL SAFETY NET
    # ================================================================

    except Exception:
        logger.exception(
            "[Graph] Unexpected unhandled error "
            "in regularisation_node"
        )

        error_message = (
            "I couldn't process your regularization request right now — please try again in a moment."
        )

        try:
            writer({
                "type": "done",
                "intent": "regularization_error",
                "is_hr": True,
                "data": {
                    "answer": error_message,
                    "node_type": "error",
                },
                "message": error_message,
                "usage_events": usage_events,
            })

        except Exception:
            logger.exception(
                "[Graph] Failed to send regularisation "
                "error event"
            )

        return {
            "response_text": error_message,
            "usage_events": usage_events,
        }