from dataclasses import dataclass
from datetime import date, datetime
from typing import Callable, Awaitable, Optional, Any
import inspect
import logging
import re

from langgraph.types import StreamWriter
from schema.agent import HRState
from services import slot_store
import services.date_query_resolver as date_query_resolver
from services.ai_service import (
    _call_llm,
    _extract_text,
    _safe_json_parse,
    _normalize_usage,
    INTENT_MODEL,
    LLM_TASK_MAX_TOKENS,
)

logger = logging.getLogger(__name__)


class _SkipExtraction(Exception):
    """Internal: this turn's action is already known (see is_explicit_confirm)."""


def _call_refusal_hook(hook, error: str, entry: dict):
    """correctable_refusal(error, entry) when the hook takes the entry (so it
    can say something about the times actually sent), else (error)."""
    import inspect
    try:
        takes_entry = len(inspect.signature(hook).parameters) >= 2
    except (TypeError, ValueError):
        takes_entry = False
    return hook(error, entry) if takes_entry else hook(error)


def _company_today() -> date:
    """Company-local calendar date (QUOTA_TIMEZONE), the same "today" every
    other check in these flows uses (attendance._today). Not date.today():
    the server's own clock can be a day behind - live, at 11:33 PM server
    time "today" resolved to 08-Oct (Asia/Kolkata) and was then refused at
    submit as a future date "on or before today (07 Oct 2026)"."""
    import os
    from zoneinfo import ZoneInfo
    return datetime.now(ZoneInfo(os.getenv("QUOTA_TIMEZONE", "UTC"))).date()


@dataclass
class SlotFlowConfig:
    name: str
    required_fields: list[str]
    field_labels: dict[str, str]
    build_prompt: Callable[[str, dict, date], str]
    submit: Callable[..., Awaitable[dict]]

    format_summary: Optional[Callable[[dict], str]] = None
    format_success: Optional[Callable[[dict, dict], str]] = None

    enrich_slots: Optional[Callable[..., Awaitable[dict]]] = None
    extract_failure_message: Optional[Callable[[dict, dict], Any]] = None
    map_submit_exception: Optional[Callable[[Exception], Optional[str]]] = None
    # A ceiling, not a target — only the tokens actually used are billed.
    # It was 250: the race reasoning model spends part of the budget on hidden
    # reasoning, so a regularization reply stopped with finish_reason=length
    # mid-JSON (measured: "start (in) time 10 am, the end (out) time 7 pm, and
    # the reason is miss punch" needed 265) and nothing was extracted — the
    # flow asked again for the three fields it had just been given.
    llm_max_tokens: int = LLM_TASK_MAX_TOKENS

    entry_fields: Optional[list[str]] = None
    entry_field_labels: Optional[dict[str, str]] = None
    entry_key: str = "date"
    format_multi_summary: Optional[Callable[[list[dict]], str]] = None
    format_multi_success: Optional[Callable[[list[dict], list[dict]], str]] = None

    # A submit refusal the employee can fix in the form itself (e.g. times
    # that don't fit their shift): given the backend's message, returns
    # {"fields": [...], "message": str} - the fields to correct and what to say
    # - or None. Such a refusal brings the FORM back (status
    # "correction_required") instead of a final "not submitted" card.
    correctable_refusal: Optional[Callable[[str], Optional[dict]]] = None
    # Checked on every entry just before submitting; returns the same shape as
    # correctable_refusal ({"fields": [...], "message": str}) when the entry
    # cannot be sent as it is - the form comes back and nothing is sent.
    pre_submit_check: Optional[Callable[[dict], Optional[dict]]] = None
    # Called on every merged entry once per turn, after normalize_entry_field.
    # May correct the entry IN PLACE and returns a sentence saying what it
    # changed (shown ahead of the turn's reply), or None - e.g. regularization
    # times outside the employee's shift brought to the shift's edges.
    align_entry: Optional[Callable[[dict], Optional[str]]] = None
    # Fields read straight off the employee's message ({field: value}) that
    # replace the model's extraction for those fields - e.g. a reason given as
    # "reason: ...", which must be submitted exactly as typed.
    verbatim_fields: Optional[Callable[[str], Optional[dict]]] = None
    is_explicit_cancel: Optional[Callable[[str], bool]] = None
    # Optional per-field clean-up of every entry after a turn's merge:
    # (field, value) -> value.
    normalize_entry_field: Optional[Callable[[str, Any], Any]] = None

    # When set, a message it accepts is a CONFIRM without asking the LLM —
    # the same deterministic-first rule as is_explicit_cancel's guard. Live
    # (regularization): a plain go-ahead depended entirely on the extraction
    # call reading it as "confirm", and an empty or odd reply defaulted to
    # provide_info, which re-showed "Shall I go ahead and submit this?".
    is_explicit_confirm: Optional[Callable[[str], bool]] = None
    # True when a message that EDITS the form also says to send it ("reason is
    # late arrival then submit"). The turn is then a confirm whatever the
    # extraction called it - live, the model labelled it provide_info and the
    # review card came back instead of the request being sent.
    ends_with_confirm: Optional[Callable[[str], bool]] = None

    # When set, called with the message when the LLM extraction returned no
    # entry at all; a non-empty dict it returns is used as this turn's entry
    # (a missing date resolves to the pending entry as usual). A floor under
    # a failed or truncated extraction, not a second extractor.
    fallback_extract_entry: Optional[Callable[[str], Optional[dict]]] = None

    # NEW — when set, any entry-level date (config.entry_key) that resolves
    # to later than today is rejected deterministically rather than
    # accepted and submitted. Regularisation exists to correct attendance
    # that ALREADY happened, so a future date can never be valid there,
    # regardless of what the LLM extracted it as.
    reject_future_dates: bool = False

    # NEW — called with (target_employee, bearer_token) right after
    # target_employee is determined for the turn, in both the single- and
    # multi-entry flows below. Returns the (possibly corrected)
    # target_employee — e.g. regularisation_node.py uses this to null out a
    # name the LLM extracted that turns out to be the caller's OWN name
    # (from their JWT), so "regularize Mukesh's attendance" said BY Mukesh
    # submits as a normal self-request instead of being treated as acting
    # on a named employee. Optional — flows with no such concept (or that
    # never set employee_name at all) simply don't set this.
    normalize_employee_name: Optional[Callable[[Optional[str], Optional[str]], Optional[str]]] = None

    # When set, a request naming ANOTHER employee (target_employee still set
    # after normalize_employee_name) is refused with this message and the
    # draft dropped - for flows where nobody may act on someone else's behalf
    # (regularization: every employee applies for their own attendance).
    other_employee_refusal: Optional[str] = None

    # NEW — called once per merged entry that still has a missing field,
    # AFTER this turn's parse+merge. Signature:
    #   async def fn(entry: dict, writer: StreamWriter) -> dict
    # Return value is merged into the entry for any field it doesn't
    # already have.
    fetch_entry_prefill: Optional[Callable[[dict, StreamWriter], Awaitable[dict]]] = None

    # NEW — intent string used when fetch_entry_prefill marks an entry
    # "_blocked" (see the fetch_entry_prefill loop in _run_multi_entry_flow)
    # AND nothing else is left pending this turn. None (the default) keeps
    # the OLD behavior: the block reason is just prepended to whatever the
    # normal "which date(s)?" continuation would say, under the usual
    # f"{config.name}_incomplete" intent. regularisation_node.py sets this to
    # "regularisation_classify" so a date rejected HERE (mid-flow, via an
    # LLM-extracted date the classify gate's own deterministic-only resolver
    # couldn't catch up front — e.g. a typo'd month name) is reported with
    # the EXACT SAME intent/shape as regularisation_eligibility_node's own
    # rejections, instead of a different-looking "regularization_incomplete"
    # with a confusing "which date(s)?" tacked on for a request that was
    # just rejected.
    blocked_entry_intent: Optional[str] = None

    # NEW — called with the LAST blocked entry when the short-circuit above
    # fires, to build extra fields for the response "data" payload (e.g.
    # regularisation_node.py adds {"regularisation_classification_status":
    # False, "date": ...}). Ignored when blocked_entry_intent is None.
    blocked_entry_extra_data: Optional[Callable[[dict], dict]] = None


_TODAY_WORD_RE = re.compile(r"\btoday\b", re.IGNORECASE)

# A bare "9-6"/"10-45"-shaped reply (two 1-2 digit numbers, dash or slash,
# no year) is exactly as readable as a shorthand time range/typo'd clock
# time as it is a DD-MM date — see the deterministic-date-fallback comment
# in _run_multi_entry_flow below for why this one shape is excluded from
# that fallback once an entry is already pending.
_AMBIGUOUS_BARE_NUMERIC_DATE_RE = re.compile(r"^\s*\d{1,2}\s*[/-]\s*\d{1,2}\s*$")


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


def _missing_fields_message(
    config: SlotFlowConfig,
    missing: list[str],
) -> str:

    label = config.name.replace("_", " ")

    phrases = [
        config.field_labels[f]
        for f in missing
    ]

    if len(phrases) == 1:
        return (
            f"I still need {phrases[0]} "
            f"to submit your {label} request."
        )

    return (
        "I still need "
        + ", ".join(phrases[:-1])
        + f", and {phrases[-1]} "
        f"to submit your {label} request."
    )


def _guard_cancel_action(config: SlotFlowConfig, action: str, query: str, parsed: dict) -> str:
    """Returns the (possibly corrected) action. If the LLM classified the
    message as "cancel" but the flow has a is_explicit_cancel check and
    the raw message doesn't actually contain cancel language, downgrade
    to "provide_info" with no new entries instead of discarding the
    in-progress request."""
    if action != "cancel":
        return action

    if config.is_explicit_cancel is None:
        return action

    if config.is_explicit_cancel(query):
        return action

    logger.info(
        f"[Graph] {config.name}: overriding LLM cancel guess for "
        f"low-signal message {query!r} -> provide_info"
    )
    parsed["entries"] = parsed.get("entries") or []
    parsed["action"] = "provide_info"
    return "provide_info"


async def run_slot_flow(config, state, writer, prefill_slots=None, candidate_dates=None):
    if config.entry_fields:
        if not (config.format_multi_summary and config.format_multi_success):
            raise ValueError(
                f"[{config.name}] entry_fields is set but "
                f"format_multi_summary/format_multi_success are missing."
            )

        return await _run_multi_entry_flow(
            config, state, writer,
            candidate_dates=candidate_dates,
        )
    if not (config.format_summary and config.format_success):
        raise ValueError(
            f"[{config.name}] single-entry flow requires "
            f"format_summary/format_success."
        )
    query = state["query"]
    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", []))
    label = config.name.replace("_", " ")

    def _finish(
        message: str,
        intent: Optional[str] = None,
        extra_data: Optional[dict] = None
    ) -> dict:
        data = {"answer": message}
        if extra_data:
            data.update(extra_data)

        writer({
            "type": "done",
            "intent": intent or config.name,
            "is_hr": True,
            "data": data,
            "message": message,
            "usage_events": usage_events,
        })

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

    today = _company_today()

    existing_slots = slot_store.get_slots(
        config.name,
        company_id,
        conversation_id,
    ) or {}

    if prefill_slots:
        for key, value in prefill_slots.items():
            if value and not existing_slots.get(key):
                existing_slots[key] = value

    if prefill_slots:
        slot_store.set_slots(
            config.name,
            company_id,
            conversation_id,
            existing_slots,
        )

    try:
        prompt = config.build_prompt(
            query,
            existing_slots,
            today,
        )

        raw = await _call_llm(
            prompt,
            max_tokens=config.llm_max_tokens,
            model=INTENT_MODEL,
        )

        parsed = _safe_json_parse(
            _extract_text(raw)
        ) or {}

        usage = (
            _normalize_usage(raw.get("usage"))
            if isinstance(raw, dict)
            else None
        )

        if usage:
            usage_events.append({
                "source": f"{config.name}_slot_extraction",
                "usage": usage,
            })

    except Exception as e:
        logger.warning(
            f"[Graph] {config.name} extraction failed: {e}"
        )
        parsed = {}

    action = parsed.get("action", "provide_info")
    action = _guard_cancel_action(config, action, query, parsed)

    if action == "cancel":
        slot_store.clear_slots(
            config.name,
            company_id,
            conversation_id,
        )

        return _finish(
            f"No problem, I've cancelled the {label} request.",
            intent=f"{config.name}_cancelled",
        )

    target_employee = (
        parsed.get("employee_name")
        or existing_slots.get("employee_name")
    )
    if config.normalize_employee_name:
        target_employee = config.normalize_employee_name(target_employee, bearer_token)
    if target_employee and config.other_employee_refusal:
        slot_store.clear_slots(config.name, company_id, conversation_id)
        return _finish(config.other_employee_refusal, intent=f"{config.name}_other_employee",
                       extra_data={"other_employee": target_employee})

    merged = dict(existing_slots)

    for f in config.required_fields:
        value = parsed.get(f)

        if value:
            merged[f] = value

    if target_employee:
        merged["employee_name"] = target_employee

    missing = [
        f
        for f in config.required_fields
        if not merged.get(f)
    ]

    if action == "confirm":

        if missing:
            slot_store.set_slots(
                config.name,
                company_id,
                conversation_id,
                merged,
            )

            return _finish(
                _missing_fields_message(config, missing),
                intent=f"{config.name}_incomplete",
            )

        writer({
            "type": f"submitting_{config.name}",
            "message": f"Submitting your {label} request...",
        })

        try:
            result = await config.submit(
                merged,
                bearer_token=bearer_token,
                company_id=company_id,
                conversation_id=conversation_id,
            )

        except Exception as e:
            logger.warning(
                f"[Graph] {config.name} submit failed: {e}"
            )

            custom = (
                config.map_submit_exception(e)
                if config.map_submit_exception
                else None
            )

            return _finish(
                custom
                or "I couldn't reach the HR system right now — "
                   "please try again shortly.",
                intent=f"{config.name}_failed",
            )

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

        if http_status is not None and http_status >= 400:

            slot_store.set_slots(
                config.name,
                company_id,
                conversation_id,
                merged,
            )

            custom = None
            if config.extract_failure_message:
                custom = config.extract_failure_message(merged, body)
                if inspect.isawaitable(custom):
                    custom = await custom

            failure_message = (
                custom
                or body.get("message")
                or body.get("msg")
                or body.get("error")
                or f"I couldn't submit your {label} request right now."
            )

            return _finish(
                failure_message,
                intent=f"{config.name}_failed",
            )

        slot_store.clear_slots(
            config.name,
            company_id,
            conversation_id,
        )

        return _finish(
            config.format_success(merged, body),
            intent=f"{config.name}_submitted",
            extra_data={
                config.name: merged,
                "erp_response": body,
            },
        )

    slot_store.set_slots(
        config.name,
        company_id,
        conversation_id,
        merged,
    )

    if missing:
        return _finish(
            _missing_fields_message(config, missing),
            intent=f"{config.name}_incomplete",
        )

    writer({
        "type": f"{config.name}_summary",
        "data": merged,
    })

    return _finish(
        config.format_summary(merged),
        intent=f"{config.name}_awaiting_confirmation",
        extra_data={
            config.name: merged,
        },
    )


def _merge_entries(
    existing: list[dict],
    incoming: list[dict],
    entry_key: str,
) -> list[dict]:
    """Always-single-entry merge: this flow tracks one date in progress
    at a time rather than accumulating a list. The LAST entry in
    `incoming` either fills in more fields for the date already pending
    (same key — merged in place, existing values kept unless overridden)
    or names a different date, in which case it REPLACES the pending
    entry outright rather than being appended alongside it. If a single
    message names more than one date, only the last one mentioned
    survives. Product decision: repeatedly asking "regularize <date>"
    for a series of distinct dates was accumulating a growing array and
    re-prompting for every earlier date each turn (observed bug) — the
    fix is to just keep the one date currently being worked on."""
    if not incoming:
        return [dict(e) for e in existing]

    latest = incoming[-1]
    key = latest.get(entry_key)
    if not key:
        return [dict(e) for e in existing]

    match = next((e for e in existing if e.get(entry_key) == key), None)
    if match:
        merged_entry = dict(match)
        merged_entry.update({k: v for k, v in latest.items() if v})
        # CHANGED — a correction clears the stale failure marker; a
        # fresh submit attempt will re-tag it if it fails again.
        merged_entry.pop("_failed", None)
        return [merged_entry]

    return [dict(latest)]


def _missing_entry_fields_message(
    config: SlotFlowConfig,
    entries_missing: list[tuple[dict, list[str]]],
) -> str:
    label = config.name.replace("_", " ")
    parts = []

    for entry, missing in entries_missing:
        date_label = entry.get(config.entry_key) or "one of the dates"
        phrases = [config.entry_field_labels[f] for f in missing]

        if len(phrases) == 1:
            parts.append(f"for {date_label}: {phrases[0]}")
        else:
            parts.append(
                f"for {date_label}: "
                + ", ".join(phrases[:-1])
                + f", and {phrases[-1]}"
            )

    return (
        f"I still need a few more details to submit your {label} "
        f"request — " + "; ".join(parts) + "."
    )


def _entries_missing_to_prompt(
    entries_missing: list[tuple[dict, list[str]]],
    touched_keys: set,
    entry_key: str,
) -> list[tuple[dict, list[str]]]:
    """Narrows which incomplete entries to actually ask about this turn.

    Without this, every reply re-lists every still-incomplete entry from
    earlier turns too — e.g. ask about date A, then the employee adds
    date B, and the follow-up re-asks for A's fields even though the
    employee already saw that question and simply moved on to B first
    (observed bug). Only the entry(ies) touched by the current message
    should be asked about; entries left untouched this turn stay pending
    silently (still visible on the entry card) until the employee's
    message touches them again. Falls back to the full list when the
    message didn't touch any entry (e.g. a bare "ok") so the employee
    still gets a prompt instead of silence.
    """
    if not touched_keys:
        return entries_missing

    touched_missing = [
        (e, m) for e, m in entries_missing if e.get(entry_key) in touched_keys
    ]
    return touched_missing or entries_missing


def _entry_snapshot(config: SlotFlowConfig, entry: dict) -> dict:
    return {f: entry.get(f) for f in (config.entry_fields or [])}


def _is_unchanged_refusal(config: SlotFlowConfig, entry: dict) -> bool:
    """True when the backend already refused this entry and none of its fields
    has changed since — confirming it again would send the identical request."""
    refused = entry.get("_refused")
    return (isinstance(refused, dict)
            and refused.get("fields") == _entry_snapshot(config, entry))


def _build_entry_cards(
    config: SlotFlowConfig,
    entries: list[dict],
    status: str,
    results: Optional[list[dict]] = None,
) -> dict:
    """Structured, frontend-renderable payload for the multi-entry card:
    one row per entry with current field values, which fields are still
    missing, whether the row is currently editable, and (post-submit)
    that entry's individual result.

    status: "incomplete" | "awaiting_confirmation" | "correction_required" |
            "submitted" | "partial" | "failed" | "cancelled"
    """

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

    cards = []
    for i, entry in enumerate(entries):
        result = results[i] if results and i < len(results) else None
        cards.append({
            "id": entry.get(config.entry_key) or f"entry_{i}",
            **{f: entry.get(f) for f in config.entry_fields},
            "missing_fields": _missing_for(entry),
            # Which fields the backend's refusal says to fix (correction_required).
            "fields_to_correct": list(entry.get("_correct_fields") or []),
            "editable": status in ("incomplete", "awaiting_confirmation", "correction_required"),
            "result": (
                {"ok": result["ok"], "error": result.get("error")}
                if result else None
            ),
        })

    if status == "incomplete":
        actions = ["edit"]
    elif status in ("awaiting_confirmation", "correction_required"):
        actions = ["edit", "confirm", "cancel"]
    else:
        actions = []

    return {
        "status": status,
        "entries": cards,
        "actions": actions,
    }


async def _run_multi_entry_flow(
    config: SlotFlowConfig,
    state: HRState,
    writer: StreamWriter,
    candidate_dates: Optional[list] = None,   # prefill_entries param REMOVED
) -> dict:

    query = state["query"]
    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", []))
    label = config.name.replace("_", " ")

    future_date_warning: Optional[str] = None

    # NEW — set below, right after config.fetch_entry_prefill runs, when
    # that hook marked an entry "_blocked" (regularisation_node.py's
    # eligibility gate: attendance status not Absent/Half Day Absent, or
    # the date is outside the regularization window). Same prepend
    # treatment as future_date_warning above.
    blocked_entry_warning: Optional[str] = None
    # What config.align_entry corrected this turn - see below.
    alignment_notice: Optional[str] = None

    def _finish(message, intent=None, extra_data=None, prepend_warnings=True):
        if prepend_warnings and future_date_warning:
            message = f"{future_date_warning}\n\n{message}"
        if prepend_warnings and blocked_entry_warning:
            message = f"{blocked_entry_warning}\n\n{message}"
        if alignment_notice:
            message = f"{alignment_notice}\n\n{message}"
        data = {"answer": message}
        if extra_data:
            data.update(extra_data)
        writer({
            "type": "done",
            "intent": intent or config.name,
            "is_hr": True,
            "data": data,
            "message": message,
            "usage_events": usage_events,
        })
        return {"response_text": message, "usage_events": usage_events}

    def _emit_card(entries, status, results=None):
        writer({
            "type": f"{config.name}_card",
            "data": _build_entry_cards(config, entries, status, results),
        })

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

    def _pre_submit_correction(entries, target):
        """Problems the flow can see BEFORE sending (config.pre_submit_check):
        the form comes back with the message and nothing is sent. None when
        there are none. Run before the summary as well as at the "yes" -
        the summary used to offer to submit "25:00–18:30" (negative run,
        28 Oct, #25), a request that could only be refused."""
        if not config.pre_submit_check:
            return None
        pre = [config.pre_submit_check(e) for e in entries]
        if not any(pre):
            return None
        results = [{"ok": not p, "body": {}, "error": (p or {}).get("message")}
                   for p in pre]
        for e, p in zip(entries, pre):
            e["_correct_fields"] = list((p or {}).get("fields") or [])
        slot_store.set_slots(
            config.name, company_id, conversation_id,
            {"entries": entries, "employee_name": target},
        )
        _emit_card(entries, "correction_required", results)
        logger.info(f"[Graph] {config.name}: pre-submit check - form shown again, "
                    f"nothing sent")
        return _finish(
            "\n\n".join(dict.fromkeys(p["message"] for p in pre if p)),
            intent=f"{config.name}_correction_required",
            extra_data={
                config.name: entries,
                "results": results,
                "is_conceled": False,
                "correction_required": True,
                "fields_to_correct": sorted({f for p in pre if p
                                             for f in p.get("fields") or []}),
            },
        )

    today = _company_today()

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

    # OLD prefill_entries block REMOVED from here entirely.

    explicit_confirm = bool(config.is_explicit_confirm and existing_entries
                            and config.is_explicit_confirm(query))
    try:
        if explicit_confirm:
            # Nothing to extract from a bare go-ahead; the stored entries are
            # what is being confirmed.
            logger.info(f"[Graph] {config.name}: explicit go-ahead {query!r} — confirming")
            raise _SkipExtraction()
        prompt = config.build_prompt(
            query, {"entries": existing_entries}, today, candidate_dates,
        )
        raw = await _call_llm(
            prompt, max_tokens=config.llm_max_tokens, model=INTENT_MODEL,
        )
        parsed = _safe_json_parse(_extract_text(raw)) or {}

        usage = (
            _normalize_usage(raw.get("usage"))
            if isinstance(raw, dict) else None
        )
        if usage:
            usage_events.append({
                "source": f"{config.name}_slot_extraction",
                "usage": usage,
            })
    except _SkipExtraction:
        parsed = {"action": "confirm", "entries": []}
    except Exception as e:
        logger.warning(f"[Graph] {config.name} extraction failed: {e}")
        parsed = {}

    action = parsed.get("action", "provide_info")
    action = _guard_cancel_action(config, action, query, parsed)
    if action == "provide_info" and config.ends_with_confirm and config.ends_with_confirm(query):
        logger.info(f"[Graph] {config.name}: edit + go-ahead in one message - confirming")
        action = "confirm"

    if action == "cancel":
        slot_store.clear_slots(config.name, company_id, conversation_id)
        _emit_card([], "cancelled")
        return _finish(
            f"No problem, I've cancelled the {label} request.",
            intent=f"{config.name}_cancelled",
            extra_data={"is_conceled": True},
        )

    target_employee = parsed.get("employee_name") or employee_name
    if config.normalize_employee_name:
        target_employee = config.normalize_employee_name(target_employee, bearer_token)
    if target_employee and config.other_employee_refusal:
        slot_store.clear_slots(config.name, company_id, conversation_id)
        return _finish(config.other_employee_refusal, intent=f"{config.name}_other_employee",
                       extra_data={"other_employee": target_employee})
    incoming_entries = parsed.get("entries") or []

    if action == "provide_info" and not incoming_entries and config.fallback_extract_entry:
        fallback_entry = dict(config.fallback_extract_entry(query) or {})
        fallback_entry.pop("_times_from_bare_range", None)
        if fallback_entry:
            logger.info(f"[Graph] {config.name}: extraction returned no entry — "
                        f"using the deterministic read {fallback_entry}")
            incoming_entries = [fallback_entry]
    elif (action == "provide_info" and len(incoming_entries) == 1
            and config.fallback_extract_entry):
        # The model returned the entry but left fields empty that the
        # message plainly states ("10 - 23 late arrival" came back with no
        # times): fill only those gaps from the deterministic read.
        fallback_entry = dict(config.fallback_extract_entry(query) or {})
        if (fallback_entry.pop("_times_from_bare_range", None)
                and len(existing_entries) == 1 and existing_entries[0].get(config.entry_key)
                and incoming_entries[0].get(config.entry_key) != existing_entries[0][config.entry_key]):
            # "10 - 23" is the times for the date in progress, not a new date
            # (the model reads it as 23-Oct): keep the date, take the times.
            logger.info(f"[Graph] {config.name}: a bare hour range read as a date "
                        f"({incoming_entries[0].get(config.entry_key)}) - keeping "
                        f"{existing_entries[0][config.entry_key]}")
            incoming_entries = [{**incoming_entries[0],
                                 config.entry_key: existing_entries[0][config.entry_key],
                                 "start_time": fallback_entry.get("start_time"),
                                 "end_time": fallback_entry.get("end_time")}]
        gaps = {k: v for k, v in fallback_entry.items()
                if v and not incoming_entries[0].get(k)}
        if gaps:
            logger.info(f"[Graph] {config.name}: filling {sorted(gaps)} from the "
                        f"deterministic read")
            incoming_entries = [{**incoming_entries[0], **gaps}]

    # An entry naming no date answers for the ONE date already in progress
    # (this flow works on one at a time - see _merge_entries). Without its
    # date the merge drops it, and "10 - 23 late arrival" read correctly was
    # thrown away all the same.
    if (len(incoming_entries) == 1 and not incoming_entries[0].get(config.entry_key)
            and len(existing_entries) == 1 and existing_entries[0].get(config.entry_key)):
        incoming_entries = [{**incoming_entries[0],
                             config.entry_key: existing_entries[0][config.entry_key]}]

    # The employee's own words win over the model's reading of them for the
    # fields a flow marks verbatim (QA TC-056: a long reason came back from the
    # model shortened, and was submitted as if the employee had written that).
    # Applied only when this turn targets exactly one entry.
    if config.verbatim_fields and len(incoming_entries) == 1:
        verbatim = config.verbatim_fields(query) or {}
        if verbatim:
            incoming_entries = [{**incoming_entries[0], **verbatim}]

    # Deterministic fallback — mirrors punch_details.py's own date
    # resolution (date_query_resolver, not dependent on the LLM catching
    # it): when this turn's LLM extraction came back with no entry at all,
    # a bare date-only reply must still resolve — both on the very first
    # turn ("which date(s) would you like to regularize?" -> "yesterday")
    # and on a LATER turn where an entry is already pending and the
    # employee names a genuinely different date to correct it to ("day
    # before yesterday", "07/09/2026") — observed live: the LLM reliably
    # caught some bare-date corrections (e.g. "tomorrow", rejected below as
    # a future date) but silently dropped others, leaving the stale
    # pending date in the "I still need..." prompt with no indication the
    # employee's reply was ever seen.
    #
    # The one shape deliberately EXCLUDED once an entry is already pending
    # is a bare two-number dash/slash pair with no year ("9-6", "10-45") —
    # date_query_resolver reads that as an explicit DD-MM date exactly as
    # readily as it could be a shorthand time range or a typo'd clock time,
    # and once fields are pending, a time reply is far more likely than a
    # new date. Same collision the deterministic invalid-date guard further
    # below (see its own comment) limits to the empty-slate turn only, for
    # the same reason. Every other shape (weekday names, "yesterday"/
    # "tomorrow"/"today", day+month name, or a numeric date WITH a year) is
    # unambiguous and always safe to resolve.
    if action == "provide_info" and not incoming_entries:
        ambiguous_bare_numeric_pair = bool(existing_entries) and _AMBIGUOUS_BARE_NUMERIC_DATE_RE.match(query)
        if not ambiguous_bare_numeric_pair:
            fallback_resolved = date_query_resolver.resolve(query, today)
            if isinstance(fallback_resolved, dict) and fallback_resolved.get("type") == "single":
                incoming_entries = [{config.entry_key: fallback_resolved["date"].isoformat()}]

    today_iso = today.strftime("%Y-%m-%d")
    existing_dates = {
        e.get(config.entry_key) for e in existing_entries if e.get(config.entry_key)
    }
    # Which existing entry(ies) a date-less update ("change the reason to
    # traffic delay", with no date repeated) could plausibly apply to.
    #
    # Restricted to INCOMPLETE/failed entries when there's more than one
    # entry in play — with several pending at once, an update that names no
    # date genuinely is ambiguous, and guessing wrong would silently
    # corrupt the WRONG entry.
    #
    # But when there's exactly ONE entry overall, that ambiguity doesn't
    # exist regardless of whether it's still missing fields or already
    # complete and awaiting confirmation — confirmed live/reported: an
    # employee correcting an already-complete entry ("actually change the
    # reason to traffic delay") got "I couldn't tell which date that's for"
    # and the correction was silently dropped, because the old filter here
    # excluded complete entries outright, leaving NO entry "resolvable" to
    # attach a date-less correction to even though only one existed. A
    # correction to an already-filled field is exactly the case this whole
    # flow needs to support smoothly — including being corrected again and
    # again, each time landing on the one entry in play.
    resolvable_existing = (
        list(existing_entries) if len(existing_entries) == 1
        else [e for e in existing_entries if _missing_for(e) or e.get("_failed")]
    )

    resolved_incoming = []
    unresolved_updates = []

    # True when the CURRENT message explicitly names today's date — either
    # the literal word "today", or an explicit reference (numeric date,
    # "8 sept", a weekday name, etc.) that happens to resolve to today.
    # Both count as "explicit", not "guessed": the bug this whole
    # looks_guessed check exists for is the LLM silently DEFAULTING to
    # today despite the prompt's own "never default" rule when the message
    # has NO date reference at all — not an employee who explicitly named
    # today's date some other way. Checking only the literal word "today"
    # (as this used to) missed that second case entirely: on the day
    # September 8th, an employee typing "08 sept" — an explicit, correct
    # date reference — got treated as a guess anyway purely because it
    # happened to equal today's ISO date, discarded, and re-asked for
    # (observed bug, and the same silent-discard also broke correcting an
    # already-pending entry TO today's date, since the len(resolvable_
    # existing)==1 branch below overwrites the "guessed" date with the
    # OLD pending date instead of the employee's new one).
    query_names_today_explicitly = bool(_TODAY_WORD_RE.search(query))
    if not query_names_today_explicitly:
        _query_date = date_query_resolver.resolve(query, today)
        query_names_today_explicitly = (
            isinstance(_query_date, dict)
            and _query_date.get("type") == "single"
            and _query_date["date"] == today
        )

    for inc in incoming_entries:
        inc_date = inc.get(config.entry_key)
        looks_guessed = (not inc_date) or (
            inc_date == today_iso
            and today_iso not in existing_dates
            and not query_names_today_explicitly
        )

        if inc_date and not looks_guessed:
            resolved_incoming.append(inc)
            continue

        if len(resolvable_existing) == 1:
            inc[config.entry_key] = resolvable_existing[0][config.entry_key]
            resolved_incoming.append(inc)
        else:
            unresolved_updates.append(inc)

    if unresolved_updates:
        slot_store.set_slots(
            config.name, company_id, conversation_id,
            {"entries": existing_entries, "employee_name": target_employee},
        )
        pending_status = (
            "incomplete" if any(_missing_for(e) for e in existing_entries)
            else "awaiting_confirmation"
        )
        _emit_card(existing_entries, pending_status)

        if resolvable_existing:
            dates_str = ", ".join(
                e.get(config.entry_key) for e in resolvable_existing
            )
            msg = (
                f"I have more than one {label} entry in progress "
                f"({dates_str}) — which date does this update apply to?"
            )
        else:
            msg = (
                f"I couldn't tell which date that's for — "
                f"could you tell me the date as well?"
            )
        return _finish(msg, intent=f"{config.name}_incomplete")

    incoming_entries = resolved_incoming

    # A brand-new request naming several distinct dates at once (e.g.
    # "regularize Monday and Tuesday") used to silently collapse to just
    # the LAST date via _merge_entries below, dropping the others with no
    # word to the employee about it (observed bug). Ask which one to
    # start with instead — reusing the same candidate_dates mechanism
    # attendance.py seeds for an absentee list — and defer the
    # future-date check (below) until a single date has actually been
    # chosen, rather than validating every candidate up front.
    if not existing_entries and len(incoming_entries) > 1:
        candidate_dates_this_turn = []
        for inc in incoming_entries:
            inc_date = inc.get(config.entry_key)
            if inc_date and inc_date not in candidate_dates_this_turn:
                candidate_dates_this_turn.append(inc_date)

        if len(candidate_dates_this_turn) > 1:
            slot_store.set_slots(
                config.name, company_id, conversation_id,
                {
                    "entries": [],
                    "employee_name": target_employee,
                    "candidate_dates": candidate_dates_this_turn,
                },
            )
            _emit_card([], "incomplete")
            dates_str = ", ".join(
                _format_date_for_display(d) for d in candidate_dates_this_turn
            )
            msg = (
                f"You mentioned a few dates ({dates_str}) — which one would "
                f"you like to start with? We can go through the others "
                f"one at a time after."
            )
            return _finish(msg, intent=f"{config.name}_incomplete")

    if config.reject_future_dates and incoming_entries:
        rejected_dates = []
        valid_incoming = []
        for inc in incoming_entries:
            inc_date = inc.get(config.entry_key)
            if inc_date and inc_date > today_iso:
                rejected_dates.append(inc_date)
            else:
                valid_incoming.append(inc)

        if rejected_dates:
            incoming_entries = valid_incoming
            dates_str = ", ".join(_format_date_for_display(d) for d in rejected_dates)
            plural = "s" if len(rejected_dates) > 1 else ""
            from services.regularisation_display import future_date_message
            future_date_warning = future_date_message(
                dates_str, _format_date_for_display(today_iso), plural=bool(plural))
            if not valid_incoming:
                # The message asked for a future date and nothing else. Live
                # ("apply regularization for 15 oct" while a request for
                # another day was in progress): the refusal went out WITH the
                # old request's card, the card is what was drawn, and the
                # employee saw only the old date's form - "stuck in the same
                # loop". A new date means they have moved on, so the old
                # request is dropped and only the refusal is sent.
                slot_store.clear_slots(config.name, company_id, conversation_id)
                logger.info(f"[Graph] {config.name}: only future date(s) {rejected_dates} "
                            f"- refused, in-progress request dropped")
                return _finish(future_date_warning, intent=f"{config.name}_incomplete",
                               extra_data={"input_required": "date",
                                           "future_dates": rejected_dates},
                               prepend_warnings=False)

    # ------------------------------------------------------------------
    # A confirm/submit message that ALSO corrects the single in-progress
    # entry's date (e.g. "date: 18/08/2026, time: 9am to 10pm, confirm and
    # submit") is a correction to THAT SAME request, not the start of an
    # unrelated new one. Without this, _merge_entries' own "different
    # date -> replace outright" behavior (see its docstring) would drop
    # whatever was already collected — most importantly the reason —
    # purely because the date changed, forcing the employee to repeat it
    # despite explicitly asking to confirm and submit right there in the
    # same message (observed bug). Carrying the OLD reason forward here
    # (only when this message doesn't already give a new one) is safe
    # because a reason is date-agnostic. The old start/end time is
    # deliberately NOT carried over the same way — those belong to the
    # date being corrected AWAY FROM and would silently misrepresent the
    # new date if kept; dropping the old entry outright (rather than
    # merging into it) means the new entry's time comes only from THIS
    # message or a fresh prefill fetch for the new date below.
    #
    # Scoped to action == "confirm" only — a plain correction with no
    # confirm/submit language still goes through the normal merge and
    # still ends up back on an explicit "shall I submit this?" card
    # exactly as before.
    # ------------------------------------------------------------------
    if action == "confirm" and len(existing_entries) == 1 and incoming_entries:
        only_existing = existing_entries[0]
        latest_incoming = incoming_entries[-1]
        new_date = latest_incoming.get(config.entry_key)
        if new_date and new_date != only_existing.get(config.entry_key):
            if not latest_incoming.get("reason") and only_existing.get("reason"):
                latest_incoming = {**latest_incoming, "reason": only_existing["reason"]}
                incoming_entries = incoming_entries[:-1] + [latest_incoming]
            existing_entries = []

    # Only the last-mentioned date actually survives the merge below —
    # keep touched_keys in sync so the "ask about what changed" message
    # (see _entries_missing_to_prompt) matches what's actually pending.
    touched_keys = (
        {incoming_entries[-1].get(config.entry_key)}
        if incoming_entries and incoming_entries[-1].get(config.entry_key)
        else set()
    )

    merged_entries = _merge_entries(
        existing_entries, incoming_entries, config.entry_key,
    )
    if config.normalize_entry_field:
        # e.g. regularization times to 24-hour "HH:MM" - "11 pm" from a typed
        # reply must reach the card and the backend as "23:00".
        merged_entries = [
            {k: (config.normalize_entry_field(k, v) if k in (config.entry_fields or []) else v)
             for k, v in e.items()}
            for e in merged_entries
        ]
    if config.align_entry:
        # Only entries whose times THIS message gave - a stored entry is never
        # re-corrected behind the employee's back on a later "yes".
        timed_now = {e.get(config.entry_key) for e in incoming_entries
                     if e.get("start_time") or e.get("end_time")}
        notes = [n for n in (config.align_entry(e) for e in merged_entries
                             if e.get(config.entry_key) in timed_now) if n]
        alignment_notice = " ".join(notes) or None

    # NEW — fetch prefill using THIS TURN's merged entries, so a date
    # parsed out of the current message is covered on the same turn.
    if config.fetch_entry_prefill:
        for entry in merged_entries:
            if entry.get("_prefill_fetched"):
                continue
            try:
                prefill = await config.fetch_entry_prefill(entry, writer)
            except Exception as e:
                logger.warning(
                    f"[Graph] {config.name} prefill fetch failed for "
                    f"{entry.get(config.entry_key)}: {e}"
                )
                prefill = None
            entry["_prefill_fetched"] = True
            if prefill:
                for k, v in prefill.items():
                    if v and not entry.get(k):
                        entry[k] = v

        # NEW — config.fetch_entry_prefill can determine an entry's date is
        # INELIGIBLE altogether (regularisation_node.py: attendance status
        # not Absent/Half Day Absent, or outside the regularization window)
        # by marking the entry it was handed "_blocked"/"_block_reason".
        # Dropped here rather than asked about further — there's no start/
        # end time or reason worth collecting for a date that can never be
        # submitted anyway.
        blocked = [e for e in merged_entries if e.get("_blocked")]
        if blocked:
            merged_entries = [e for e in merged_entries if not e.get("_blocked")]
            blocked_entry_warning = "\n\n".join(
                e.get("_block_reason") or f"{e.get(config.entry_key)} isn't eligible for {label}."
                for e in blocked
            )

            # NEW — nothing else survived this turn: report this exactly
            # like config.blocked_entry_intent (regularisation_node.py:
            # "regularisation_classify", matching regularisation_eligibility_
            # node's own rejections) rather than falling through to the
            # generic "which date(s)?" continuation below under
            # f"{config.name}_incomplete" — a request that was JUST
            # rejected shouldn't come back looking like an unrelated,
            # still-open question. Only short-circuits when NOTHING else is
            # pending; an entry that survives (a different, still-valid
            # date) keeps the normal continuation, with the warning merely
            # prepended, unchanged from before.
            if not merged_entries and config.blocked_entry_intent:
                slot_store.set_slots(
                    config.name, company_id, conversation_id,
                    {"entries": [], "employee_name": target_employee},
                )
                _emit_card([], "incomplete")
                extra = (
                    config.blocked_entry_extra_data(blocked[-1])
                    if config.blocked_entry_extra_data else None
                )
                return _finish(
                    blocked_entry_warning, intent=config.blocked_entry_intent,
                    extra_data=extra, prepend_warnings=False,
                )

    entries_missing = [
        (e, m) for e in merged_entries for m in [_missing_for(e)] if m
    ]

    if action == "confirm":
        if not merged_entries or entries_missing:
            slot_store.set_slots(
                config.name, company_id, conversation_id,
                {"entries": merged_entries, "employee_name": target_employee},
            )
            _emit_card(merged_entries, "incomplete")
            msg = (
                _missing_entry_fields_message(config, entries_missing)
                if entries_missing else
                f"I don't have any {label} details to submit yet — "
                f"could you tell me the date(s)?"
            )
            return _finish(msg, intent=f"{config.name}_incomplete")

        # The request the backend already REFUSED, confirmed again unchanged.
        # Live: erp-api answered "Regularization has already been applied for
        # the selected date"; the entry was kept for a retry, and every later
        # "yes" / "submit" / Confirm & Submit posted the identical request and
        # got the identical refusal — a loop with no way out. A refusal is an
        # answer about THIS request, so sending it again unchanged can only get
        # the same answer; the employee is told what would change it instead.
        # A timeout or outage is not marked (_refused_snapshot), so those still
        # retry as before.
        def _correction_form(entries, results, prefix=""):
            """The FORM again, for a refusal the employee can fix in it (see
            SlotFlowConfig.correctable_refusal) - or None when any failed entry's
            refusal is not of that kind."""
            if not config.correctable_refusal or not entries:
                return None
            fixes = []
            for e, r in zip(entries, results):
                fix = (_call_refusal_hook(config.correctable_refusal, r.get("error") or "", e)
                       if not r.get("ok") else None)
                if not fix:
                    return None
                fixes.append(fix)
            for e, fix in zip(entries, fixes):
                e["_correct_fields"] = list(fix.get("fields") or [])
            slot_store.set_slots(
                config.name, company_id, conversation_id,
                {"entries": entries, "employee_name": target_employee},
            )
            _emit_card(entries, "correction_required", results)
            messages = list(dict.fromkeys(f["message"] for f in fixes))
            return _finish(
                prefix + "\n\n".join(messages),
                intent=f"{config.name}_correction_required",
                extra_data={
                    config.name: entries,
                    "results": results,
                    "is_conceled": False,
                    "correction_required": True,
                    "fields_to_correct": sorted({f for fix in fixes for f in fix.get("fields") or []}),
                },
            )

        if all(_is_unchanged_refusal(config, e) for e in merged_entries):
            reasons = list(dict.fromkeys(e["_refused"]["error"] for e in merged_entries))
            results = [{"ok": False, "body": {}, "error": e["_refused"]["error"]}
                       for e in merged_entries]
            # Still the same times the backend refused: the form again, not a
            # dead end (nothing is sent).
            correction = _correction_form(merged_entries, results)
            if correction is not None:
                logger.info(f"[Graph] {config.name}: unchanged refused entry - form shown again")
                return correction
            slot_store.set_slots(
                config.name, company_id, conversation_id,
                {"entries": merged_entries, "employee_name": target_employee},
            )
            _emit_card(merged_entries, "partial", results)
            logger.info(f"[Graph] {config.name}: not resubmitting an unchanged, refused request")
            reason_text = "\n".join(f"- {r}" for r in reasons)
            return _finish(
                f"I can't submit this {label} request as it is:\n\n{reason_text}\n\n"
                f"Sending it again unchanged would get the same answer. Change the date "
                f"or another detail and I'll try again — or say **cancel** to stop.",
                intent=f"{config.name}_partial",
                extra_data={
                    config.name: merged_entries,
                    "results": results,
                    "is_conceled": False,
                    "resubmit_blocked": True,
                },
            )

        _correction = _pre_submit_correction(merged_entries, target_employee)
        if _correction:
            return _correction

        writer({
            "type": f"submitting_{config.name}",
            "message": f"Submitting your {label} request...",
        })

        results = []
        for entry in merged_entries:
            full_entry = dict(entry)
            if target_employee:
                full_entry["employee_name"] = target_employee

            try:
                result = await config.submit(
                    full_entry,
                    bearer_token=bearer_token,
                    company_id=company_id,
                    conversation_id=conversation_id,
                )
                http_status = result.get("http_status")
                body = result.get("body") or {}

                if http_status is not None and http_status >= 400:
                    custom = None
                    if config.extract_failure_message:
                        custom = config.extract_failure_message(entry, body)
                        if inspect.isawaitable(custom):
                            custom = await custom

                    err = (
                        custom or body.get("message") or body.get("msg")
                        or body.get("error") or "Submission failed."
                    )
                    # refused: the backend ANSWERED about this request (a 4xx
                    # with its reason). Only these are held against a resubmit.
                    results.append({"ok": False, "body": body, "error": err,
                                    "refused": http_status < 500})
                else:
                    results.append({"ok": True, "body": body, "error": None})

            except Exception as e:
                logger.warning(
                    f"[Graph] {config.name} submit failed for "
                    f"{entry.get(config.entry_key)}: {e}"
                )
                custom = (
                    config.map_submit_exception(e)
                    if config.map_submit_exception else None
                )
                results.append({
                    "ok": False, "body": {},
                    "error": custom or "Couldn't reach the HR system.",
                })

        failed_entries = [
            e for e, r in zip(merged_entries, results) if not r["ok"]
        ]

        # NEW — mark failed entries so a same-turn dateless correction
        # can still be resolved to this entry on the next turn.
        for e, r in zip(merged_entries, results):
            if not r["ok"]:
                e["_failed"] = True
            else:
                e.pop("_failed", None)
            # What exactly was refused — see _is_unchanged_refusal.
            if r.get("refused"):
                e["_refused"] = {"fields": _entry_snapshot(config, e), "error": r["error"]}
            else:
                e.pop("_refused", None)
            e.pop("_correct_fields", None)

        # Every failed entry refused for something fixable in the form (e.g.
        # times that don't fit the shift): bring the form back with what to
        # change, instead of a final "not submitted". Only when nothing in this
        # submit went through, so a partial success is never hidden.
        if failed_entries and len(failed_entries) == len(merged_entries):
            correction = _correction_form(
                failed_entries, [r for r in results if not r["ok"]])
            if correction is not None:
                return correction

        if failed_entries:
            slot_store.set_slots(
                config.name, company_id, conversation_id,
                {"entries": failed_entries, "employee_name": target_employee},
            )
        else:
            slot_store.clear_slots(config.name, company_id, conversation_id)

        status = "submitted" if not failed_entries else "partial"
        _emit_card(merged_entries, status, results)

        return _finish(
            config.format_multi_success(merged_entries, results),
            intent=f"{config.name}_{status}",
            extra_data={
                config.name: merged_entries,
                "results": results,
                "is_conceled": False,
            },
        )

    # provide_info
    slot_store.set_slots(
        config.name, company_id, conversation_id,
        {"entries": merged_entries, "employee_name": target_employee},
    )

    if not merged_entries:
        # No card: there is nothing on it yet. Live, this empty card was drawn
        # as "Regularization Request Identified" with a blank date and Apply
        # Now / Not Now, so "apply regularisation" never visibly asked for the
        # date. The question goes out on its own, marked as waiting for one.
        return _finish(
            "Sure — which date(s) would you like to regularize?",
            intent=f"{config.name}_incomplete",
            extra_data={"input_required": "date"},
        )

    if not entries_missing:
        _correction = _pre_submit_correction(merged_entries, target_employee)
        if _correction:
            return _correction

    status = "incomplete" if entries_missing else "awaiting_confirmation"
    _emit_card(merged_entries, status)

    if entries_missing:
        prompt_missing = _entries_missing_to_prompt(
            entries_missing, touched_keys, config.entry_key,
        )
        return _finish(
            _missing_entry_fields_message(config, prompt_missing),
            intent=f"{config.name}_incomplete",
        )

    writer({"type": f"{config.name}_summary", "data": merged_entries})

    return _finish(
        config.format_multi_summary(merged_entries),
        intent=f"{config.name}_awaiting_confirmation",
        extra_data={config.name: merged_entries, "is_conceled": False},
    )