"""Slack helpers for seller-facing Deal Desk intake."""

from __future__ import annotations

import json
import re
from dataclasses import dataclass
from typing import Any, Literal

from g_gremlin.autopilot.contracts import PlanV1
from g_gremlin.dealdesk.service import (
    CloseReviewSubmissionV1,
    QuoteIntentV1,
    SellerContactRoleResultV1,
    SellerDealHealthSummaryV1,
    SellerDealLookupResultV1,
    SellerFieldFixResultV1,
    SellerQuoteRevisionApprovalContextV1,
    SellerQuoteRevisionPreviewV1,
    SellerQuoteRevisionApplyResultV1,
    SellerQuoteStatusResultV1,
)

_OPPORTUNITY_ID_RE = re.compile(r"\b006[a-zA-Z0-9]{12,15}\b", re.IGNORECASE)
_CONTACT_ID_RE = re.compile(r"\b003[a-zA-Z0-9]{12,15}\b", re.IGNORECASE)
_EMAIL_RE = re.compile(r"\b[^\s@]+@[^\s@]+\.[^\s@]+\b")
_ORG_ALIAS_TOKEN_RE = re.compile(r"(?:--org\s+|org[:=])([a-zA-Z0-9._-]+)", re.IGNORECASE)
_FIELD_ASSIGNMENT_RE = re.compile(r"\b([A-Za-z][A-Za-z0-9_]*)\s*(?:=|:)\s*(.+)")
_ROLE_ASSIGNMENT_RE = re.compile(r"\brole\s*(?:=|:)\s*(.+)$", re.IGNORECASE)


@dataclass(frozen=True)
class SlackDealDeskSellerCommand:
    action: Literal["deal_health", "quote_status", "quote_preview", "submit_for_close", "fix_missing_field", "add_contact_role"]
    opportunity_id: str | None = None
    deal_query: str | None = None
    org_alias: str | None = None
    field_name: str | None = None
    field_value: str | None = None
    contact_reference: str | None = None
    role_name: str | None = None
    quote_operation: str | None = None
    quote_requested_value: str | None = None
    raw_text: str = ""


def seller_command_usage_text() -> str:
    return (
        "Use `/dealdesk health 006...` or `/dealdesk where is Acme renewal`, `/dealdesk submit 006...`, "
        "`/dealdesk quote 006...` or `/dealdesk what's the quote status on Acme renewal`, "
        "`/dealdesk change quote discount on 006... to 10%`, "
        "`/dealdesk preview add product SKU-123 on Acme renewal qty 5`, "
        "`/dealdesk preview change quote quantity on Acme renewal for SKU-123 to 5`, "
        "`/dealdesk fix 006... FieldApiName=Value`, "
        "or `/dealdesk contact 006... contact@company.com role=Decision Maker`. "
        "You can optionally append `--org your-org-alias`."
    )


def parse_seller_command(text: str) -> SlackDealDeskSellerCommand:
    normalized = " ".join(str(text or "").strip().split())
    if not normalized:
        raise ValueError(seller_command_usage_text())

    opportunity_match = _OPPORTUNITY_ID_RE.search(normalized)
    org_alias_match = _ORG_ALIAS_TOKEN_RE.search(normalized)
    org_alias = org_alias_match.group(1).strip() if org_alias_match else None
    lowered = normalized.lower()
    normalized_without_org = _ORG_ALIAS_TOKEN_RE.sub("", normalized).strip()
    assignment_match = _FIELD_ASSIGNMENT_RE.search(normalized_without_org)
    quote_preview_request = _parse_quote_preview_request(normalized_without_org)

    submit_phrases = (
        "submit for close",
        "submit close",
        "submit this deal for close",
        "request close review",
        "close review",
    )
    quote_phrases = (
        "quote status",
        "quote approval",
        "approval state",
        "who still needs to approve",
        "who needs to approve",
        "still needs to approve",
        "stale or conflicting quote",
        "stale quote",
        "conflicting quote",
    )
    health_phrases = (
        "what is blocking",
        "what's blocking",
        "blocking close",
        "where is",
        "deal health",
        "health",
        "status",
        "blockers",
    )
    fix_phrases = ("fix ", "set ", "update ")
    contact_phrases = ("contact ", "add contact ", "add-contact ", "attach contact ")

    if quote_preview_request is not None:
        field_name = None
        field_value = None
        contact_reference = None
        role_name = None
        quote_operation = quote_preview_request["operation"]
        quote_requested_value = quote_preview_request["requested_value"]
        action: Literal["deal_health", "quote_status", "quote_preview", "submit_for_close", "fix_missing_field", "add_contact_role"] = "quote_preview"
    elif assignment_match and lowered.startswith(fix_phrases):
        field_name = assignment_match.group(1).strip()
        field_value = _strip_balanced_quotes(assignment_match.group(2).strip())
        if not field_name or not field_value:
            raise ValueError(
                "Field fixes must use `FieldApiName=Value`. "
                f"{seller_command_usage_text()}"
            )
        contact_reference = None
        role_name = None
        quote_operation = None
        quote_requested_value = None
        action: Literal["deal_health", "submit_for_close", "fix_missing_field", "add_contact_role"] = "fix_missing_field"
    elif lowered.startswith(contact_phrases):
        role_match = _ROLE_ASSIGNMENT_RE.search(normalized_without_org)
        if role_match is None:
            raise ValueError(
                "Contact adds must include `role=Role Name`. "
                f"{seller_command_usage_text()}"
            )
        role_name = _strip_balanced_quotes(role_match.group(1).strip())
        prefix_payload = normalized_without_org[: role_match.start()].strip()
        prefix_payload = re.sub(r"^(?:add[- ]contact|attach contact|contact)\s+", "", prefix_payload, flags=re.IGNORECASE)
        if opportunity_match is not None:
            prefix_payload = prefix_payload.replace(opportunity_match.group(0), "", 1).strip()
        contact_match = _CONTACT_ID_RE.search(prefix_payload) or _EMAIL_RE.search(prefix_payload)
        if contact_match is None:
            raise ValueError(
                "Contact adds require an existing Salesforce Contact id or exact contact email. "
                f"{seller_command_usage_text()}"
            )
        field_name = None
        field_value = None
        contact_reference = contact_match.group(0).strip()
        quote_operation = None
        quote_requested_value = None
        if not role_name:
            raise ValueError(
                "Contact adds must include a non-empty `role=Role Name` value. "
                f"{seller_command_usage_text()}"
            )
        action = "add_contact_role"
    elif lowered.startswith("submit ") or any(phrase in lowered for phrase in submit_phrases):
        field_name = None
        field_value = None
        contact_reference = None
        role_name = None
        quote_operation = None
        quote_requested_value = None
        action = "submit_for_close"
    elif lowered.startswith("quote ") or lowered.startswith("approvals ") or any(phrase in lowered for phrase in quote_phrases):
        field_name = None
        field_value = None
        contact_reference = None
        role_name = None
        quote_operation = None
        quote_requested_value = None
        action = "quote_status"
    elif any(phrase in lowered for phrase in health_phrases):
        field_name = None
        field_value = None
        contact_reference = None
        role_name = None
        quote_operation = None
        quote_requested_value = None
        action = "deal_health"
    else:
        field_name = None
        field_value = None
        contact_reference = None
        role_name = None
        quote_operation = None
        quote_requested_value = None
        action = "deal_health"

    if opportunity_match is None:
        if action not in {"deal_health", "quote_status", "quote_preview"}:
            raise ValueError(
                "Seller writes and close submissions still require an explicit opportunity id. "
                f"{seller_command_usage_text()}"
            )
        if action == "quote_preview" and quote_preview_request is not None:
            deal_query = _strip_balanced_quotes(str(quote_preview_request["deal_reference"])).strip(" ?")
        else:
            deal_query = _extract_deal_query(normalized_without_org)
        if not deal_query:
            raise ValueError(
                "Deal Desk Slack intake could not determine which active deal you mean. "
                f"{seller_command_usage_text()}"
            )
        opportunity_id = None
    else:
        deal_query = None
        opportunity_id = opportunity_match.group(0)

    return SlackDealDeskSellerCommand(
        action=action,
        opportunity_id=opportunity_id,
        deal_query=deal_query,
        org_alias=org_alias,
        field_name=field_name,
        field_value=field_value,
        contact_reference=contact_reference,
        role_name=role_name,
        quote_operation=quote_operation,
        quote_requested_value=quote_requested_value,
        raw_text=normalized,
    )


def build_seller_deal_health_blocks(summary: SellerDealHealthSummaryV1) -> dict[str, Any]:
    action_payload = _seller_action_payload(summary.opportunity_id, summary.org_alias)
    quick_fix_action = _seller_quick_fix_action(summary)
    contact_action = _seller_contact_action(summary)
    blocks: list[dict[str, Any]] = [
        {
            "type": "header",
            "text": {"type": "plain_text", "text": "Deal Desk Health"},
        },
        {
            "type": "section",
            "text": {
                "type": "mrkdwn",
                "text": (
                    f"*Deal:* `{summary.opportunity_id}`\n"
                    f"*State:* {_humanize_token(summary.lifecycle_state)}\n"
                    f"*Close Workflow:* {_humanize_token(summary.close_workflow_state)}"
                ),
            },
        },
        {
            "type": "context",
            "elements": [
                {"type": "mrkdwn", "text": f"Blockers: {summary.blocker_count}"},
                {"type": "mrkdwn", "text": f"Warnings: {summary.warning_count}"},
                {"type": "mrkdwn", "text": f"Confidence: {summary.overall_confidence:.2f}"},
            ],
        },
    ]

    issue_lines = _issue_lines(summary)
    if issue_lines:
        blocks.append(
            {
                "type": "section",
                "text": {"type": "mrkdwn", "text": "*Current Issues*\n" + "\n".join(issue_lines)},
            }
        )

    close_review_lines = _latest_close_review_lines(summary)
    if close_review_lines:
        blocks.append(
            {
                "type": "section",
                "text": {"type": "mrkdwn", "text": "*Latest Close Review*\n" + "\n".join(close_review_lines)},
            }
        )

    action_lines = _action_lines(summary.next_actions)
    if action_lines:
        blocks.append(
            {
                "type": "section",
                "text": {"type": "mrkdwn", "text": "*Suggested Next Steps*\n" + "\n".join(action_lines)},
            }
        )

    command_hints = [_fix_command_hint(summary), _contact_command_hint(summary)]
    for command_hint in [hint for hint in command_hints if hint]:
        blocks.append(
            {
                "type": "context",
                "elements": [{"type": "mrkdwn", "text": str(command_hint)}],
            }
        )

    if summary.latest_reconciliation_packet_id:
        blocks.append(
            {
                "type": "context",
                "elements": [
                    {
                        "type": "mrkdwn",
                        "text": f"Latest packet: `{summary.latest_reconciliation_packet_id}`",
                    }
                ],
            }
        )

    blocks.append(
        {
            "type": "actions",
            "elements": _seller_health_action_elements(
                summary=summary,
                action_payload=action_payload,
                quick_fix_action=quick_fix_action,
                contact_action=contact_action,
            ),
        }
    )

    return {
        "text": (
            f"Deal Desk health for {summary.opportunity_id}: "
            f"{summary.blocker_count} blocker(s), {summary.warning_count} warning(s)."
        ),
        "blocks": blocks,
    }


def build_seller_quote_status_blocks(summary: SellerQuoteStatusResultV1) -> dict[str, Any]:
    action_payload = _seller_action_payload(summary.opportunity_id, summary.org_alias)
    selected_quote = summary.selected_quote
    if selected_quote is not None:
        summary_text = (
            f"Quote status for {summary.opportunity_id}: "
            f"{selected_quote.label} is {selected_quote.status} and approval is {summary.approval_state}."
        )
    else:
        summary_text = (
            f"Quote status for {summary.opportunity_id}: "
            f"{_humanize_token(summary.status)}."
        )

    blocks: list[dict[str, Any]] = [
        {
            "type": "header",
            "text": {"type": "plain_text", "text": "Quote Status"},
        },
        {
            "type": "section",
            "text": {
                "type": "mrkdwn",
                "text": (
                    f"*Deal:* `{summary.opportunity_id}`\n"
                    f"*Quote Stack:* {_humanize_token(summary.detected_engine)}\n"
                    f"*Coverage:* {_humanize_token(summary.status)}"
                    + (f"\n*Current Quote:* {_quote_record_headline(summary.selected_quote)}" if summary.selected_quote else "")
                ),
            },
        },
        {
            "type": "context",
            "elements": [
                {"type": "mrkdwn", "text": f"Approval: {_humanize_token(summary.approval_state)}"},
                {"type": "mrkdwn", "text": f"Quotes found: {summary.quote_count}"},
                {"type": "mrkdwn", "text": f"Stale: {'Yes' if summary.stale else 'No'}"},
                {"type": "mrkdwn", "text": f"Conflict: {'Yes' if summary.conflict else 'No'}"},
            ],
        },
    ]

    quote_lines = _quote_record_lines(summary.selected_quote)
    if quote_lines:
        blocks.append(
            {
                "type": "section",
                "text": {"type": "mrkdwn", "text": "*Current Quote*\n" + "\n".join(quote_lines)},
            }
        )

    approval_lines = _quote_approval_lines(summary)
    if approval_lines:
        blocks.append(
            {
                "type": "section",
                "text": {"type": "mrkdwn", "text": "*Approval State*\n" + "\n".join(approval_lines)},
            }
        )

    signal_lines = _quote_signal_lines(summary)
    if signal_lines:
        blocks.append(
            {
                "type": "section",
                "text": {"type": "mrkdwn", "text": "*Quote Signals*\n" + "\n".join(signal_lines)},
            }
        )

    additional_quote_lines = _quote_inventory_lines(summary.additional_quotes)
    if additional_quote_lines:
        blocks.append(
            {
                "type": "section",
                "text": {"type": "mrkdwn", "text": "*Other Supported Quotes*\n" + "\n".join(additional_quote_lines)},
            }
        )

    coverage_lines = _quote_coverage_lines(summary)
    if coverage_lines:
        blocks.append(
            {
                "type": "section",
                "text": {"type": "mrkdwn", "text": "*Coverage And Gaps*\n" + "\n".join(coverage_lines)},
            }
        )

    evidence_lines = _quote_evidence_lines(summary.evidence)
    if evidence_lines:
        blocks.append(
            {
                "type": "section",
                "text": {"type": "mrkdwn", "text": "*Evidence Used*\n" + "\n".join(evidence_lines)},
            }
        )

    if summary.next_step:
        blocks.append(
            {
                "type": "section",
                "text": {"type": "mrkdwn", "text": f"*Next Step*\n{summary.next_step}"},
            }
        )

    if summary.latest_reconciliation_packet_id:
        blocks.append(
            {
                "type": "context",
                "elements": [
                    {
                        "type": "mrkdwn",
                        "text": f"Latest packet: `{summary.latest_reconciliation_packet_id}`",
                    }
                ],
            }
        )

    blocks.append(
        {
            "type": "actions",
            "elements": [
                {
                    "type": "button",
                    "text": {"type": "plain_text", "text": "Refresh Quote Status"},
                    "style": "primary",
                    "action_id": "dealdesk_seller_refresh_quote_status",
                    "value": action_payload,
                },
                {
                    "type": "button",
                    "text": {"type": "plain_text", "text": "Refresh Health"},
                    "action_id": "dealdesk_seller_refresh_health",
                    "value": action_payload,
                },
            ],
        }
    )

    return {
        "text": summary_text,
        "blocks": blocks,
    }


def build_seller_quote_revision_preview_blocks(
    preview: SellerQuoteRevisionPreviewV1,
) -> dict[str, Any]:
    action_payload = _quote_preview_action_payload(preview.intent)
    summary_text = (
        f"Quote change preview for {preview.opportunity_id}: "
        f"{preview.intent.target_label} -> {preview.intent.requested_value_display}."
    )
    blocks: list[dict[str, Any]] = [
        {
            "type": "header",
            "text": {"type": "plain_text", "text": "Quote Change Preview"},
        },
        {
            "type": "section",
            "text": {
                "type": "mrkdwn",
                "text": (
                    f"*Deal:* `{preview.opportunity_id}`\n"
                    f"*Requested Change:* {preview.intent.target_label} -> `{preview.intent.requested_value_display}`\n"
                    f"*Quote Stack:* {_humanize_token(preview.detected_engine)}\n"
                    f"*Execution:* Preview Only"
                    + (
                        f"\n*Current Quote:* `{preview.selected_quote.label}` ({_humanize_token(preview.selected_quote.status)})"
                        if preview.selected_quote is not None
                        else ""
                    )
                ),
            },
        },
        {
            "type": "context",
            "elements": [
                {"type": "mrkdwn", "text": f"Status: {_humanize_token(preview.status)}"},
                {"type": "mrkdwn", "text": f"Policy: {_humanize_token(preview.preview_policy_state)}"},
                {"type": "mrkdwn", "text": f"Approval: {_humanize_token(preview.approval_state)}"},
                {"type": "mrkdwn", "text": f"Readiness: {_humanize_token(preview.preview_readiness_mode)}"},
            ],
        },
    ]

    if preview.field_preview is not None:
        blocks.append(
            {
                "type": "section",
                "text": {
                    "type": "mrkdwn",
                    "text": (
                        "*Field Preview*\n"
                        f"- *Resolved field:* `{preview.field_preview.object_name}.{preview.field_preview.field_name}`\n"
                        f"- *Current value:* `{preview.field_preview.current_value_display}`\n"
                        f"- *Proposed value:* `{preview.field_preview.proposed_value_display}`"
                    ),
                },
            }
        )
    elif preview.line_item_preview is not None:
        line_item_lines = _quote_line_item_preview_lines(preview.line_item_preview)
        if line_item_lines:
            blocks.append(
                {
                    "type": "section",
                    "text": {"type": "mrkdwn", "text": "*Line Item Preview*\n" + "\n".join(line_item_lines)},
                }
            )

    policy_lines = _quote_preview_policy_lines(preview)
    if policy_lines:
        blocks.append(
            {
                "type": "section",
                "text": {"type": "mrkdwn", "text": "*Policy Signals*\n" + "\n".join(policy_lines)},
            }
        )

    coverage_lines = _quote_preview_coverage_lines(preview)
    if coverage_lines:
        blocks.append(
            {
                "type": "section",
                "text": {"type": "mrkdwn", "text": "*Coverage And Gaps*\n" + "\n".join(coverage_lines)},
            }
        )

    evidence_lines = _quote_evidence_lines(preview.evidence)
    if evidence_lines:
        blocks.append(
            {
                "type": "section",
                "text": {"type": "mrkdwn", "text": "*Evidence Used*\n" + "\n".join(evidence_lines)},
            }
        )

    if preview.next_step:
        blocks.append(
            {
                "type": "section",
                "text": {"type": "mrkdwn", "text": f"*Next Step*\n{preview.next_step}"},
            }
        )

    action_elements: list[dict[str, Any]] = []
    if preview.apply_supported and preview.preview_policy_state in {"clean", "approval_likely"}:
        action_elements.append(
            {
                "type": "button",
                "text": {
                    "type": "plain_text",
                    "text": "Apply Change" if preview.preview_policy_state == "clean" else "Request Approval",
                },
                "style": "primary",
                "action_id": "dealdesk_seller_apply_quote_change",
                "value": action_payload,
            }
        )
    action_elements.append(
        {
            "type": "button",
            "text": {"type": "plain_text", "text": "Refresh Preview"},
            "action_id": "dealdesk_seller_preview_quote_change",
            "value": action_payload,
        }
    )
    action_elements.append(
        {
            "type": "button",
            "text": {"type": "plain_text", "text": "Refresh Quote Status"},
            "action_id": "dealdesk_seller_refresh_quote_status",
            "value": _seller_action_payload(preview.opportunity_id, preview.org_alias),
        }
    )
    blocks.append({"type": "actions", "elements": action_elements})

    return {
        "text": summary_text,
        "blocks": blocks,
    }


def build_seller_quote_revision_apply_result_blocks(
    result: SellerQuoteRevisionApplyResultV1,
    *,
    routing_note: str | None = None,
) -> dict[str, Any]:
    action_payload = _quote_preview_action_payload(result.intent)
    if result.applied:
        headline = "Quote Change Applied"
        status_line = "Applied"
    elif result.approval_required:
        headline = "Quote Change Pending Approval"
        status_line = "Approval Required"
    elif result.already_set:
        headline = "Quote Already Matches"
        status_line = "Already Set"
    else:
        headline = "Quote Change Not Applied"
        status_line = _humanize_token(result.receipt_outcome)

    blocks: list[dict[str, Any]] = [
        {
            "type": "header",
            "text": {"type": "plain_text", "text": headline},
        },
        {
            "type": "section",
            "text": {
                "type": "mrkdwn",
                "text": (
                    f"*Deal:* `{result.opportunity_id}`\n"
                    f"*Requested Change:* {result.intent.target_label} -> `{result.intent.requested_value_display}`\n"
                    f"*Status:* {status_line}"
                ),
            },
        },
    ]

    if result.field_preview is not None:
        blocks.append(
            {
                "type": "section",
                "text": {
                    "type": "mrkdwn",
                    "text": (
                        "*Applied Field*\n"
                        f"- *Resolved field:* `{result.field_preview.object_name}.{result.field_preview.field_name}`\n"
                        f"- *Previous value:* `{result.field_preview.current_value_display}`\n"
                        f"- *Target value:* `{result.field_preview.proposed_value_display}`"
                    ),
                },
            }
        )
    elif result.line_item_preview is not None:
        line_item_lines = _quote_line_item_preview_lines(result.line_item_preview)
        if line_item_lines:
            blocks.append(
                {
                    "type": "section",
                    "text": {"type": "mrkdwn", "text": "*Line Item Change*\n" + "\n".join(line_item_lines)},
                }
            )

    context_elements = [
        {"type": "mrkdwn", "text": f"Policy: {_humanize_token(result.preview_policy_state)}"},
        {
            "type": "mrkdwn",
            "text": f"Quote status: {_humanize_token(result.updated_quote_status.status)}",
        },
    ]
    if result.approval_required and result.pending_run_id:
        context_elements.insert(0, {"type": "mrkdwn", "text": f"Pending run: `{result.pending_run_id}`"})
    elif result.receipt_run_id:
        context_elements.insert(0, {"type": "mrkdwn", "text": f"Receipt run: `{result.receipt_run_id}`"})
    blocks.append({"type": "context", "elements": context_elements})

    if routing_note:
        blocks.append(
            {
                "type": "section",
                "text": {"type": "mrkdwn", "text": routing_note},
            }
        )

    updated_lines = _quote_apply_updated_status_lines(result.updated_quote_status)
    if updated_lines:
        blocks.append(
            {
                "type": "section",
                "text": {"type": "mrkdwn", "text": "*Updated Quote Status*\n" + "\n".join(updated_lines)},
            }
        )

    if result.updated_quote_status.next_step:
        blocks.append(
            {
                "type": "section",
                "text": {"type": "mrkdwn", "text": f"*Next Step*\n{result.updated_quote_status.next_step}"},
            }
        )

    blocks.append(
        {
            "type": "actions",
            "elements": [
                {
                    "type": "button",
                    "text": {"type": "plain_text", "text": "Preview Again"},
                    "action_id": "dealdesk_seller_preview_quote_change",
                    "value": action_payload,
                },
                {
                    "type": "button",
                    "text": {"type": "plain_text", "text": "Refresh Quote Status"},
                    "action_id": "dealdesk_seller_refresh_quote_status",
                    "value": _seller_action_payload(result.opportunity_id, result.org_alias),
                },
            ],
        }
    )

    return {
        "text": (
            f"Quote change result for {result.opportunity_id}: "
            f"{status_line.lower()}."
        ),
        "blocks": blocks,
    }


def build_seller_quote_revision_approval_request_blocks(
    context: SellerQuoteRevisionApprovalContextV1,
    *,
    plan: PlanV1,
    approve_token: str,
) -> dict[str, Any]:
    value_payload = json.dumps(
        {
            "run_id": plan.run_id,
            "plan_hash": plan.plan_hash or "",
            "policy_hash": plan.policy_hash or "",
            "approve_token": approve_token,
        }
    )
    summary_text = (
        f"Quote change approval required for {context.opportunity_id}: "
        f"{context.intent.target_label} -> {context.intent.requested_value_display}."
    )
    policy_lines = [f"- *Policy state:* {_humanize_token(context.preview_policy_state)}"]
    if context.matched_approval_route_names:
        policy_lines.append(
            "- *Matched routes:* " + ", ".join(f"`{item}`" for item in context.matched_approval_route_names[:4])
        )
    if context.recommended_approval_roles:
        policy_lines.append(
            "- *Recommended approvers:* "
            + ", ".join(f"`{item}`" for item in context.recommended_approval_roles[:4])
        )
    policy_lines.extend(f"- {item}" for item in list(context.preview_policy_reasons or [])[:4])
    if len(context.preview_policy_reasons or []) > 4:
        policy_lines.append(f"- ... and {len(context.preview_policy_reasons) - 4} more signal(s).")

    blocks: list[dict[str, Any]] = [
        {
            "type": "header",
            "text": {"type": "plain_text", "text": "Quote Change Approval"},
        },
        {
            "type": "context",
            "elements": [
                {"type": "mrkdwn", "text": f"Run: `{plan.run_id}`"},
                {"type": "mrkdwn", "text": f"Risk: {int(getattr(plan.risk, 'max_risk_level', 0) or 0)}"},
                {"type": "mrkdwn", "text": f"Stack: {_humanize_token(context.detected_engine)}"},
            ],
        },
    ]
    if context.field_preview is not None:
        blocks.insert(
            1,
            {
                "type": "section",
                "text": {
                    "type": "mrkdwn",
                    "text": (
                        f"*Deal:* `{context.opportunity_id}`\n"
                        f"*Seller Ask:* {context.intent.target_label} -> `{context.intent.requested_value_display}`\n"
                        f"*Quote:* `{context.selected_quote.label}` ({_humanize_token(context.selected_quote.status)})\n"
                        f"*Resolved field:* `{context.field_preview.object_name}.{context.field_preview.field_name}`\n"
                        f"*Current -> Proposed:* `{context.field_preview.current_value_display}` -> `{context.field_preview.proposed_value_display}`"
                    ),
                },
            },
        )
    elif context.line_item_preview is not None:
        line_item_lines = _quote_line_item_preview_lines(context.line_item_preview)
        blocks.insert(
            1,
            {
                "type": "section",
                "text": {
                    "type": "mrkdwn",
                    "text": (
                        f"*Deal:* `{context.opportunity_id}`\n"
                        f"*Seller Ask:* {context.intent.target_label} -> `{context.intent.requested_value_display}`\n"
                        f"*Quote:* `{context.selected_quote.label}` ({_humanize_token(context.selected_quote.status)})\n"
                        + (
                            "*Line Item Change*\n" + "\n".join(line_item_lines)
                            if line_item_lines
                            else ""
                        )
                    ),
                },
            },
        )

    if policy_lines:
        blocks.append(
            {
                "type": "section",
                "text": {"type": "mrkdwn", "text": "*Policy And Approval Signals*\n" + "\n".join(policy_lines)},
            }
        )

    evidence_lines = _quote_evidence_lines(context.evidence, limit=4)
    if evidence_lines:
        blocks.append(
            {
                "type": "section",
                "text": {"type": "mrkdwn", "text": "*Evidence Used*\n" + "\n".join(evidence_lines)},
            }
        )

    blocks.append(
        {
            "type": "section",
            "text": {
                "type": "mrkdwn",
                "text": (
                    "*Decision*\n"
                    "Approve runs this exact quote change now with full audit trace. "
                    "Reject leaves the quote unchanged and records the decision."
                ),
            },
        }
    )
    blocks.append(
        {
            "type": "actions",
            "elements": [
                {
                    "type": "button",
                    "text": {"type": "plain_text", "text": "Approve & Run"},
                    "style": "primary",
                    "action_id": "autopilot_approve_run",
                    "value": value_payload,
                },
                {
                    "type": "button",
                    "text": {"type": "plain_text", "text": "Reject"},
                    "style": "danger",
                    "action_id": "autopilot_reject",
                    "value": value_payload,
                },
            ],
        }
    )

    return {"text": summary_text, "blocks": blocks}


def build_deal_lookup_blocks(
    result: SellerDealLookupResultV1,
    *,
    action_id: str = "dealdesk_seller_refresh_health",
    button_text: str = "Open Health",
    context_note: str = "Use the explicit opportunity id for guided writes and close submission.",
    extra_payload: dict[str, Any] | None = None,
) -> dict[str, Any]:
    if result.status == "not_found":
        blocks = [
            {
                "type": "header",
                "text": {"type": "plain_text", "text": "Deal Not Found"},
            },
            {
                "type": "section",
                "text": {
                    "type": "mrkdwn",
                    "text": (
                        f"No active deal matched `{result.query}`.\n"
                        "Try a more specific deal name or use the explicit opportunity id."
                    ),
                },
            },
        ]
        return {
            "text": f"No active deal matched {result.query}.",
            "blocks": blocks,
        }

    headline = "Select Deal" if result.status == "multiple_matches" else "Deal Match"
    blocks: list[dict[str, Any]] = [
        {
            "type": "header",
            "text": {"type": "plain_text", "text": headline},
        },
        {
            "type": "section",
            "text": {
                "type": "mrkdwn",
                "text": (
                    f"Matched {result.candidate_count} active deal(s) for `{result.query}`."
                    + (" Showing the closest matches." if result.truncated else "")
                ),
            },
        },
    ]
    for candidate in result.candidates:
        detail_lines = [
            f"*{candidate.name}* (`{candidate.opportunity_id}`)",
            f"Stage: {candidate.stage_name or 'Unknown'}",
        ]
        if candidate.account_name:
            detail_lines.append(f"Account: {candidate.account_name}")
        if candidate.close_date:
            detail_lines.append(f"Close: {candidate.close_date}")
        if candidate.owner_name:
            detail_lines.append(f"Owner: {candidate.owner_name}")
        blocks.append(
            {
                "type": "section",
                "text": {"type": "mrkdwn", "text": "\n".join(detail_lines)},
                "accessory": {
                    "type": "button",
                    "text": {"type": "plain_text", "text": button_text},
                    "action_id": action_id,
                    "value": _seller_action_payload(candidate.opportunity_id, result.org_alias, extra_payload=extra_payload),
                },
            }
        )
    blocks.append(
        {
            "type": "context",
            "elements": [
                {
                    "type": "mrkdwn",
                    "text": str(context_note),
                }
            ],
        }
    )
    return {
        "text": f"Matched {result.candidate_count} active deal(s) for {result.query}.",
        "blocks": blocks,
    }


def build_close_review_submission_blocks(
    submission: CloseReviewSubmissionV1,
    *,
    routing_note: str | None = None,
) -> dict[str, Any]:
    action_payload = _seller_action_payload(submission.opportunity_id, submission.org_alias)
    close_workflow_state = str(submission.close_workflow_state or "").strip().lower()
    if close_workflow_state == "post_close_executed":
        headline = "Post-Close Executed"
        summary_text = (
            f"Post-close execution completed for {submission.opportunity_id}: "
            f"{_humanize_token(submission.post_close_status)}."
        )
    elif close_workflow_state == "closed_won_progressed":
        headline = "Close Progressed"
        summary_text = (
            f"Final close progression completed for {submission.opportunity_id}: "
            f"{submission.progression_target_stage or 'Closed Won'}."
        )
    elif close_workflow_state == "certified":
        headline = "Close Certified"
        summary_text = (
            f"Close certification completed for {submission.opportunity_id}: "
            f"{submission.overall_disposition}."
        )
    else:
        headline = "Close Review Submitted"
        summary_text = (
            f"Close review submitted for {submission.opportunity_id}: "
            f"{submission.overall_disposition}."
        )
    blocks: list[dict[str, Any]] = [
        {
            "type": "header",
            "text": {"type": "plain_text", "text": headline},
        },
        {
            "type": "section",
            "text": {
                "type": "mrkdwn",
                "text": (
                    f"*Deal:* `{submission.opportunity_id}`\n"
                    f"*Disposition:* {_humanize_token(submission.overall_disposition)}\n"
                    f"*Close Workflow:* {_humanize_token(submission.close_workflow_state)}\n"
                    f"*Document Evidence:* {_humanize_token(submission.document_evidence_status)}\n"
                    f"*Document Verification:* {_humanize_token(submission.document_extraction_status)}\n"
                    f"*Quote Integrity:* {_humanize_token(submission.quote_integrity_status)}\n"
                    f"*Final Close:* {_humanize_token(submission.progression_status)}"
                    f"{f' -> {submission.progression_target_stage}' if submission.progression_target_stage else ''}"
                    f"\n*Post-Close:* {_humanize_token(submission.post_close_status)}"
                ),
            },
        },
        {
            "type": "context",
            "elements": [
                {"type": "mrkdwn", "text": f"Packet: `{submission.reconciliation_packet_id}`"},
                {"type": "mrkdwn", "text": f"Blockers: {submission.blocker_count}"},
                {
                    "type": "mrkdwn",
                    "text": f"Approval Required: {submission.approval_required_count}",
                },
                {"type": "mrkdwn", "text": f"Auto-fixable: {submission.auto_fixable_count}"},
                {
                    "type": "mrkdwn",
                    "text": (
                        f"Docs: {submission.document_candidate_count} | "
                        f"Likely close docs: {submission.document_contract_candidate_count}"
                    ),
                },
                {
                    "type": "mrkdwn",
                    "text": (
                        f"Evidence rows: {submission.document_evidence_count} | "
                        f"Field comparisons: {submission.document_comparison_count} | "
                        f"Doc discrepancies: {submission.document_discrepancy_count}"
                    ),
                },
                {
                    "type": "mrkdwn",
                    "text": (
                        f"Quote fingerprints: {submission.quote_fingerprint_count} | "
                        f"Binary mismatches: {submission.quote_binary_mismatch_count} | "
                        f"Semantic mismatches: {submission.quote_semantic_mismatch_count}"
                    ),
                },
            ],
        },
    ]
    if submission.progression_approval_required and submission.progression_pending_run_id:
        blocks[2]["elements"].append(
            {
                "type": "mrkdwn",
                "text": f"Pending progression: `{submission.progression_pending_run_id}`",
            }
        )
    if submission.post_close_approval_required and submission.post_close_pending_run_id:
        blocks[2]["elements"].append(
            {
                "type": "mrkdwn",
                "text": f"Pending post-close: `{submission.post_close_pending_run_id}`",
            }
        )

    trigger_lines = [
        f"- {run.trigger_label}: {_humanize_token(run.status)}"
        + (f" ({_humanize_token(run.result_status)})" if run.result_status else "")
        for run in submission.post_close_trigger_runs
    ]
    if trigger_lines:
        blocks.append(
            {
                "type": "section",
                "text": {"type": "mrkdwn", "text": "*Post-Close Triggers*\n" + "\n".join(trigger_lines)},
            }
        )
    if submission.document_summary:
        blocks.append(
            {
                "type": "section",
                "text": {"type": "mrkdwn", "text": f"*Document Inventory*\n{submission.document_summary}"},
            }
        )
    if submission.document_evidence_summary:
        blocks.append(
            {
                "type": "section",
                "text": {"type": "mrkdwn", "text": f"*Structured Evidence*\n{submission.document_evidence_summary}"},
            }
        )
    if submission.quote_integrity_summary:
        blocks.append(
            {
                "type": "section",
                "text": {"type": "mrkdwn", "text": f"*Quote Integrity*\n{submission.quote_integrity_summary}"},
            }
        )

    if routing_note:
        blocks.append(
            {
                "type": "section",
                "text": {"type": "mrkdwn", "text": routing_note},
            }
        )

    action_lines = _action_lines(submission.next_actions)
    if action_lines:
        blocks.append(
            {
                "type": "section",
                "text": {"type": "mrkdwn", "text": "*Next Steps*\n" + "\n".join(action_lines)},
            }
        )

    blocks.append(
        {
            "type": "actions",
            "elements": [
                {
                    "type": "button",
                    "text": {"type": "plain_text", "text": "Refresh Health"},
                    "action_id": "dealdesk_seller_refresh_health",
                    "value": action_payload,
                }
            ],
        }
    )

    return {
        "text": summary_text,
        "blocks": blocks,
    }


def build_field_fix_result_blocks(
    result: SellerFieldFixResultV1,
    *,
    routing_note: str | None = None,
) -> dict[str, Any]:
    action_payload = _seller_action_payload(result.opportunity_id, result.org_alias)
    if result.applied:
        headline = "Field Fix Applied"
        status_line = "Applied"
    elif result.approval_required:
        headline = "Field Fix Pending Approval"
        status_line = "Approval Required"
    elif result.already_set:
        headline = "Field Already Set"
        status_line = "Already Set"
    else:
        headline = "Field Fix Not Applied"
        status_line = _humanize_token(result.receipt_outcome)
    blocks: list[dict[str, Any]] = [
        {
            "type": "header",
            "text": {"type": "plain_text", "text": headline},
        },
        {
            "type": "section",
            "text": {
                "type": "mrkdwn",
                "text": (
                    f"*Deal:* `{result.opportunity_id}`\n"
                    f"*Field:* `{result.field_name}`\n"
                    f"*Value:* `{result.field_value}`\n"
                    f"*Status:* {status_line}"
                ),
            },
        },
    ]

    context_elements = [
        {
            "type": "mrkdwn",
            "text": (
                f"Updated blockers: {result.updated_summary.blocker_count} | "
                f"warnings: {result.updated_summary.warning_count}"
            ),
        }
    ]
    if result.approval_required and result.pending_run_id:
        context_elements.insert(0, {"type": "mrkdwn", "text": f"Pending run: `{result.pending_run_id}`"})
    elif result.receipt_run_id:
        context_elements.insert(0, {"type": "mrkdwn", "text": f"Receipt run: `{result.receipt_run_id}`"})
    elif result.pending_run_id:
        context_elements.insert(0, {"type": "mrkdwn", "text": f"Pending run: `{result.pending_run_id}`"})
    blocks.append({"type": "context", "elements": context_elements})

    if result.already_set and result.current_value not in (None, ""):
        blocks.append(
            {
                "type": "context",
                "elements": [
                    {
                        "type": "mrkdwn",
                        "text": f"Current CRM value already matches: `{result.current_value}`",
                    }
                ],
            }
        )

    if routing_note:
        blocks.append(
            {
                "type": "section",
                "text": {"type": "mrkdwn", "text": routing_note},
            }
        )

    next_steps = _action_lines(result.updated_summary.next_actions)
    if next_steps:
        blocks.append(
            {
                "type": "section",
                "text": {"type": "mrkdwn", "text": "*Updated Next Steps*\n" + "\n".join(next_steps)},
            }
        )

    blocks.append(
        {
            "type": "actions",
            "elements": [
                {
                    "type": "button",
                    "text": {"type": "plain_text", "text": "Refresh Health"},
                    "action_id": "dealdesk_seller_refresh_health",
                    "value": action_payload,
                },
                {
                    "type": "button",
                    "text": {"type": "plain_text", "text": "Submit for Close"},
                    "style": "primary",
                    "action_id": "dealdesk_seller_submit_for_close",
                    "value": action_payload,
                },
            ],
        }
    )

    return {
        "text": (
            f"Deal Desk field fix for {result.opportunity_id}: "
            f"{result.field_name} {status_line.lower()}."
        ),
        "blocks": blocks,
    }


def build_contact_role_result_blocks(
    result: SellerContactRoleResultV1,
    *,
    routing_note: str | None = None,
) -> dict[str, Any]:
    action_payload = _seller_action_payload(result.opportunity_id, result.org_alias)
    if result.applied:
        headline = "Contact Added To Deal"
        status_line = "Applied"
    elif result.approval_required:
        headline = "Contact Add Pending Approval"
        status_line = "Approval Required"
    elif result.already_set:
        headline = "Contact Already Attached"
        status_line = "Already Set"
    else:
        headline = "Contact Add Not Applied"
        status_line = _humanize_token(result.receipt_outcome)

    contact_label = result.contact_email or result.contact_id
    blocks: list[dict[str, Any]] = [
        {
            "type": "header",
            "text": {"type": "plain_text", "text": headline},
        },
        {
            "type": "section",
            "text": {
                "type": "mrkdwn",
                "text": (
                    f"*Deal:* `{result.opportunity_id}`\n"
                    f"*Contact:* `{contact_label}`\n"
                    f"*Role:* `{result.role_name}`\n"
                    f"*Primary Field:* `{result.primary_contact_field_name}`\n"
                    f"*Status:* {status_line}"
                ),
            },
        },
    ]

    context_elements = [
        {
            "type": "mrkdwn",
            "text": (
                f"Updated blockers: {result.updated_summary.blocker_count} | "
                f"warnings: {result.updated_summary.warning_count}"
            ),
        }
    ]
    if result.approval_required and result.pending_run_id:
        context_elements.insert(0, {"type": "mrkdwn", "text": f"Pending run: `{result.pending_run_id}`"})
    elif result.receipt_run_id:
        context_elements.insert(0, {"type": "mrkdwn", "text": f"Receipt run: `{result.receipt_run_id}`"})
    blocks.append({"type": "context", "elements": context_elements})

    if result.already_set and result.current_primary_contact_id:
        blocks.append(
            {
                "type": "context",
                "elements": [
                    {
                        "type": "mrkdwn",
                        "text": f"Current primary contact already matches: `{result.current_primary_contact_id}`",
                    }
                ],
            }
        )

    if routing_note:
        blocks.append(
            {
                "type": "section",
                "text": {"type": "mrkdwn", "text": routing_note},
            }
        )

    next_steps = _action_lines(result.updated_summary.next_actions)
    if next_steps:
        blocks.append(
            {
                "type": "section",
                "text": {"type": "mrkdwn", "text": "*Updated Next Steps*\n" + "\n".join(next_steps)},
            }
        )

    blocks.append(
        {
            "type": "actions",
            "elements": [
                {
                    "type": "button",
                    "text": {"type": "plain_text", "text": "Refresh Health"},
                    "action_id": "dealdesk_seller_refresh_health",
                    "value": action_payload,
                },
                {
                    "type": "button",
                    "text": {"type": "plain_text", "text": "Submit for Close"},
                    "style": "primary",
                    "action_id": "dealdesk_seller_submit_for_close",
                    "value": action_payload,
                },
            ],
        }
    )

    return {
        "text": (
            f"Deal Desk contact add for {result.opportunity_id}: "
            f"{result.role_name} {status_line.lower()}."
        ),
        "blocks": blocks,
    }


def build_revops_close_review_alert_blocks(
    *,
    summary: SellerDealHealthSummaryV1,
    submission: CloseReviewSubmissionV1,
    seller_actor_id: str | None = None,
    source_channel: str | None = None,
) -> dict[str, Any]:
    blocks: list[dict[str, Any]] = [
        {
            "type": "header",
            "text": {"type": "plain_text", "text": "Deal Desk Close Review Exception"},
        },
        {
            "type": "section",
            "text": {
                "type": "mrkdwn",
                "text": (
                    f"*Deal:* `{submission.opportunity_id}`\n"
                    f"*Disposition:* {_humanize_token(submission.overall_disposition)}\n"
                    f"*Packet:* `{submission.reconciliation_packet_id}`"
                ),
            },
        },
        {
            "type": "context",
            "elements": [
                {"type": "mrkdwn", "text": f"Blockers: {summary.blocker_count}"},
                {"type": "mrkdwn", "text": f"Warnings: {summary.warning_count}"},
                {"type": "mrkdwn", "text": f"Confidence: {summary.overall_confidence:.2f}"},
            ],
        },
    ]

    issue_lines = _issue_lines(summary, limit=6)
    if issue_lines:
        blocks.append(
            {
                "type": "section",
                "text": {"type": "mrkdwn", "text": "*Escalation Context*\n" + "\n".join(issue_lines)},
            }
        )

    trust_lines = _submission_trust_lines(submission)
    if trust_lines:
        blocks.append(
            {
                "type": "section",
                "text": {"type": "mrkdwn", "text": "*Document And Quote Integrity*\n" + "\n".join(trust_lines)},
            }
        )

    action_lines = _action_lines(submission.next_actions or summary.next_actions)
    if action_lines:
        blocks.append(
            {
                "type": "section",
                "text": {"type": "mrkdwn", "text": "*Suggested Follow-up*\n" + "\n".join(action_lines)},
            }
        )

    context_bits: list[str] = [f"Packet path: `{submission.reconciliation_packet_path}`"]
    if seller_actor_id:
        context_bits.append(f"Seller: `{seller_actor_id}`")
    if source_channel:
        context_bits.append(f"Source channel: `{source_channel}`")
    blocks.append(
        {
            "type": "context",
            "elements": [{"type": "mrkdwn", "text": " | ".join(context_bits)}],
        }
    )

    return {
        "text": (
            f"Deal Desk close review exception for {submission.opportunity_id}: "
            f"{submission.overall_disposition}."
        ),
        "blocks": blocks,
    }


def build_seller_field_fix_modal(
    *,
    opportunity_id: str,
    field_name: str,
    org_alias: str | None = None,
    response_url: str | None = None,
) -> dict[str, Any]:
    private_metadata = {
        "opportunity_id": str(opportunity_id or "").strip(),
        "field_name": str(field_name or "").strip(),
        "org_alias": str(org_alias or "").strip(),
        "response_url": str(response_url or "").strip(),
    }
    org_hint = f"\n*Org:* `{org_alias}`" if org_alias else ""
    return {
        "type": "modal",
        "callback_id": "dealdesk_seller_fix_field_modal",
        "private_metadata": json.dumps(private_metadata),
        "title": {"type": "plain_text", "text": "Fix Missing Field"},
        "submit": {"type": "plain_text", "text": "Apply Fix"},
        "close": {"type": "plain_text", "text": "Cancel"},
        "blocks": [
            {
                "type": "section",
                "text": {
                    "type": "mrkdwn",
                    "text": (
                        f"*Deal:* `{opportunity_id}`\n"
                        f"*Field:* `{field_name}`"
                        f"{org_hint}"
                    ),
                },
            },
            {
                "type": "input",
                "block_id": "field_value_input",
                "label": {"type": "plain_text", "text": "Field value"},
                "element": {
                    "type": "plain_text_input",
                    "action_id": "field_value",
                    "placeholder": {
                        "type": "plain_text",
                        "text": f"Enter a value for {field_name}",
                    },
                },
            },
        ],
    }


def build_seller_contact_role_modal(
    *,
    opportunity_id: str,
    org_alias: str | None = None,
    response_url: str | None = None,
) -> dict[str, Any]:
    private_metadata = {
        "opportunity_id": str(opportunity_id or "").strip(),
        "org_alias": str(org_alias or "").strip(),
        "response_url": str(response_url or "").strip(),
    }
    org_hint = f"\n*Org:* `{org_alias}`" if org_alias else ""
    return {
        "type": "modal",
        "callback_id": "dealdesk_seller_contact_role_modal",
        "private_metadata": json.dumps(private_metadata),
        "title": {"type": "plain_text", "text": "Add Contact"},
        "submit": {"type": "plain_text", "text": "Attach Contact"},
        "close": {"type": "plain_text", "text": "Cancel"},
        "blocks": [
            {
                "type": "section",
                "text": {
                    "type": "mrkdwn",
                    "text": (
                        f"*Deal:* `{opportunity_id}`"
                        f"{org_hint}\n"
                        "*Enter an exact contact email or Salesforce Contact Id, then the role to attach.*"
                    ),
                },
            },
            {
                "type": "input",
                "block_id": "contact_reference_input",
                "label": {"type": "plain_text", "text": "Contact email or Salesforce Contact ID"},
                "element": {
                    "type": "plain_text_input",
                    "action_id": "contact_reference",
                    "placeholder": {
                        "type": "plain_text",
                        "text": "buyer@example.com or 003...",
                    },
                },
            },
            {
                "type": "input",
                "block_id": "role_name_input",
                "label": {"type": "plain_text", "text": "Contact role"},
                "element": {
                    "type": "plain_text_input",
                    "action_id": "role_name",
                    "placeholder": {
                        "type": "plain_text",
                        "text": "Decision Maker",
                    },
                },
            },
        ],
    }


def seller_fix_modal_fallback_text(
    *,
    opportunity_id: str,
    field_name: str,
    org_alias: str | None = None,
) -> str:
    return (
        "Guided fix modal is unavailable in this Slack context. "
        f"Use `{_seller_fix_command_text(opportunity_id, field_name, org_alias)}`."
    )


def seller_contact_modal_fallback_text(
    *,
    opportunity_id: str,
    org_alias: str | None = None,
) -> str:
    return (
        "Guided contact modal is unavailable in this Slack context. "
        f"Use `{_seller_contact_command_text(opportunity_id, org_alias)}`."
    )


def _humanize_token(value: str | None) -> str:
    token = str(value or "").strip()
    if not token:
        return "Unknown"
    return token.replace("_", " ").title()


def _seller_action_payload(
    opportunity_id: str,
    org_alias: str | None,
    extra_payload: dict[str, Any] | None = None,
) -> str:
    payload: dict[str, Any] = {
        "opportunity_id": str(opportunity_id or "").strip(),
        "org_alias": str(org_alias or "").strip(),
    }
    if isinstance(extra_payload, dict):
        for key, value in extra_payload.items():
            if value in (None, ""):
                continue
            payload[str(key)] = value
    return json.dumps(payload)


def _quote_preview_action_payload(intent: QuoteIntentV1) -> str:
    return _seller_action_payload(
        intent.opportunity_id,
        intent.org_alias,
        extra_payload={
            "quote_operation": intent.operation,
            "quote_requested_value": intent.requested_value_raw,
            "raw_text": intent.raw_request,
        },
    )


def _seller_health_action_elements(
    *,
    summary: SellerDealHealthSummaryV1,
    action_payload: str,
    quick_fix_action: Any | None,
    contact_action: Any | None,
) -> list[dict[str, Any]]:
    elements: list[dict[str, Any]] = [
        {
            "type": "button",
            "text": {"type": "plain_text", "text": "Refresh Health"},
            "action_id": "dealdesk_seller_refresh_health",
            "value": action_payload,
        }
    ]
    if quick_fix_action is not None:
        field_name = str(getattr(quick_fix_action, "field_name", "") or "").strip()
        elements.append(
            {
                "type": "button",
                "text": {"type": "plain_text", "text": f"Fix {field_name}"},
                "action_id": "dealdesk_seller_open_fix_field_modal",
                "value": json.dumps(
                    {
                        "opportunity_id": str(summary.opportunity_id or "").strip(),
                        "org_alias": str(summary.org_alias or "").strip(),
                        "field_name": field_name,
                    }
                ),
            }
        )
    if contact_action is not None:
        elements.append(
            {
                "type": "button",
                "text": {"type": "plain_text", "text": "Add Contact"},
                "action_id": "dealdesk_seller_open_contact_role_modal",
                "value": json.dumps(
                    {
                        "opportunity_id": str(summary.opportunity_id or "").strip(),
                        "org_alias": str(summary.org_alias or "").strip(),
                    }
                ),
            }
        )
    elements.append(
        {
            "type": "button",
            "text": {"type": "plain_text", "text": "Submit for Close"},
            "style": "primary",
            "action_id": "dealdesk_seller_submit_for_close",
            "value": action_payload,
        }
    )
    return elements


def _issue_lines(summary: SellerDealHealthSummaryV1, *, limit: int = 5) -> list[str]:
    rows = list(summary.blockers) + list(summary.warnings) + list(summary.infos)
    lines: list[str] = []
    for issue in rows[:limit]:
        field_text = f" (`{issue.field_name}`)" if issue.field_name else ""
        lines.append(
            f"- {_severity_prefix(issue.severity)} *{issue.code}*{field_text}: {issue.message}"
        )
    if len(rows) > limit:
        lines.append(f"- ... and {len(rows) - limit} more issue(s).")
    return lines


def _latest_close_review_lines(summary: SellerDealHealthSummaryV1) -> list[str]:
    if not summary.latest_reconciliation_packet_id:
        return []
    lines: list[str] = []
    if summary.latest_close_review_disposition:
        lines.append(
            f"- *Disposition:* {_humanize_token(summary.latest_close_review_disposition)}"
        )
    if summary.latest_document_evidence_status not in {"", "not_required"}:
        document_line = (
            f"- *Document Evidence:* {_humanize_token(summary.latest_document_evidence_status)}"
            f" | Verification: {_humanize_token(summary.latest_document_extraction_status)}"
        )
        if int(summary.latest_document_discrepancy_count or 0) > 0:
            document_line += f" | Discrepancies: {summary.latest_document_discrepancy_count}"
        lines.append(document_line)
        document_detail = ""
        if summary.latest_document_evidence_status in {"missing", "ambiguous"}:
            document_detail = str(summary.latest_document_summary or "").strip()
        elif (
            summary.latest_document_extraction_status in {"partial", "unsupported"}
            or int(summary.latest_document_discrepancy_count or 0) > 0
        ):
            document_detail = str(summary.latest_document_evidence_summary or "").strip()
        if document_detail:
            lines.append(f"- *Document Detail:* {document_detail}")
    if summary.latest_quote_integrity_status not in {"", "not_available"}:
        quote_line = f"- *Quote Integrity:* {_humanize_token(summary.latest_quote_integrity_status)}"
        quote_bits: list[str] = []
        if int(summary.latest_quote_integrity_discrepancy_count or 0) > 0:
            quote_bits.append(f"issues: {summary.latest_quote_integrity_discrepancy_count}")
        if int(summary.latest_quote_binary_mismatch_count or 0) > 0:
            quote_bits.append(f"binary mismatches: {summary.latest_quote_binary_mismatch_count}")
        if int(summary.latest_quote_semantic_mismatch_count or 0) > 0:
            quote_bits.append(f"semantic mismatches: {summary.latest_quote_semantic_mismatch_count}")
        if int(summary.latest_quote_fingerprint_count or 0) > 0:
            quote_bits.append(f"fingerprints: {summary.latest_quote_fingerprint_count}")
        if quote_bits:
            quote_line += " | " + " | ".join(quote_bits)
        lines.append(quote_line)
        if summary.latest_quote_integrity_summary:
            lines.append(f"- *Integrity Detail:* {summary.latest_quote_integrity_summary}")
    if summary.latest_close_review_generated_at:
        lines.append(f"- *Last reviewed:* `{summary.latest_close_review_generated_at}`")
    return lines


def _seller_quick_fix_action(summary: SellerDealHealthSummaryV1) -> Any | None:
    if _summary_has_revops_only_trust_gate(summary):
        return None
    for action in list(summary.next_actions or []):
        if str(getattr(action, "action_key", "") or "").strip() != "fix_missing_field":
            continue
        field_name = str(getattr(action, "field_name", "") or "").strip()
        if field_name:
            return action
    return None


def _seller_contact_action(summary: SellerDealHealthSummaryV1) -> Any | None:
    if _summary_has_revops_only_trust_gate(summary):
        return None
    for action in list(summary.next_actions or []):
        if str(getattr(action, "action_key", "") or "").strip() == "add_contact_role":
            return action
    return None


def _summary_has_revops_only_trust_gate(summary: SellerDealHealthSummaryV1) -> bool:
    evidence_status = str(summary.latest_document_evidence_status or "").strip().lower()
    if evidence_status in {"missing", "ambiguous"}:
        return True
    extraction_status = str(summary.latest_document_extraction_status or "").strip().lower()
    if extraction_status in {"unsupported", "partial"}:
        return True
    if int(summary.latest_document_discrepancy_count or 0) > 0:
        return True
    quote_status = str(summary.latest_quote_integrity_status or "").strip().lower()
    if quote_status in {"review_required", "blocked"}:
        return True
    return int(summary.latest_quote_integrity_discrepancy_count or 0) > 0


def _submission_trust_lines(submission: CloseReviewSubmissionV1) -> list[str]:
    lines: list[str] = []
    if submission.document_evidence_status not in {"", "not_required"}:
        document_line = (
            f"- *Document Evidence:* {_humanize_token(submission.document_evidence_status)}"
            f" | Verification: {_humanize_token(submission.document_extraction_status)}"
        )
        if int(submission.document_discrepancy_count or 0) > 0:
            document_line += f" | Discrepancies: {submission.document_discrepancy_count}"
        lines.append(document_line)
        document_detail = ""
        if submission.document_evidence_status in {"missing", "ambiguous"}:
            document_detail = str(submission.document_summary or "").strip()
        elif (
            submission.document_extraction_status in {"partial", "unsupported"}
            or int(submission.document_discrepancy_count or 0) > 0
        ):
            document_detail = str(submission.document_evidence_summary or "").strip()
        if document_detail:
            lines.append(f"- *Document Detail:* {document_detail}")
    if submission.quote_integrity_status not in {"", "not_available"}:
        quote_line = f"- *Quote Integrity:* {_humanize_token(submission.quote_integrity_status)}"
        quote_bits: list[str] = []
        if int(submission.quote_integrity_discrepancy_count or 0) > 0:
            quote_bits.append(f"issues: {submission.quote_integrity_discrepancy_count}")
        if int(submission.quote_binary_mismatch_count or 0) > 0:
            quote_bits.append(f"binary mismatches: {submission.quote_binary_mismatch_count}")
        if int(submission.quote_semantic_mismatch_count or 0) > 0:
            quote_bits.append(f"semantic mismatches: {submission.quote_semantic_mismatch_count}")
        if int(submission.quote_fingerprint_count or 0) > 0:
            quote_bits.append(f"fingerprints: {submission.quote_fingerprint_count}")
        if quote_bits:
            quote_line += " | " + " | ".join(quote_bits)
        lines.append(quote_line)
        if submission.quote_integrity_summary:
            lines.append(f"- *Integrity Detail:* {submission.quote_integrity_summary}")
    return lines


def _action_lines(actions: list[Any], *, limit: int = 5) -> list[str]:
    lines: list[str] = []
    for action in list(actions or [])[:limit]:
        label = str(getattr(action, "label", "") or "").strip() or str(getattr(action, "action_key", "Next Step"))
        detail = str(getattr(action, "detail", "") or "").strip()
        if detail:
            lines.append(f"- *{label}*: {detail}")
        else:
            lines.append(f"- *{label}*")
    if len(actions or []) > limit:
        lines.append(f"- ... and {len(actions or []) - limit} more next step(s).")
    return lines


def _severity_prefix(severity: str | None) -> str:
    lowered = str(severity or "").strip().lower()
    if lowered == "blocking":
        return ":red_circle:"
    if lowered == "warning":
        return ":warning:"
    return ":information_source:"


def _fix_command_hint(summary: SellerDealHealthSummaryV1) -> str | None:
    if _summary_has_revops_only_trust_gate(summary):
        return None
    for action in summary.next_actions:
        if str(getattr(action, "action_key", "") or "").strip() != "fix_missing_field":
            continue
        field_name = str(getattr(action, "field_name", "") or "").strip()
        if not field_name:
            continue
        return f"Guided fix syntax: `{_seller_fix_command_text(summary.opportunity_id, field_name, summary.org_alias)}`"
    return None


def _contact_command_hint(summary: SellerDealHealthSummaryV1) -> str | None:
    if _summary_has_revops_only_trust_gate(summary):
        return None
    for action in summary.next_actions:
        if str(getattr(action, "action_key", "") or "").strip() != "add_contact_role":
            continue
        return f"Guided contact syntax: `{_seller_contact_command_text(summary.opportunity_id, summary.org_alias)}`"
    return None


def _parse_quote_preview_request(value: str) -> dict[str, str] | None:
    text = " ".join(str(value or "").strip().split())
    text = re.sub(r"^(?:/dealdesk\s+)?", "", text, flags=re.IGNORECASE)
    patterns = (
        (
            "add_product",
            r"^(?:preview\s+)?add\s+(?:product|sku)\s+(?P<product>.+?)\s+(?:on|for)\s+(?P<deal>.+?)\s+(?:qty|quantity)\s+(?P<quantity>.+)$",
        ),
        (
            "remove_product",
            r"^(?:preview\s+)?remove\s+(?:product|sku)\s+(?P<product>.+?)\s+(?:on|for)\s+(?P<deal>.+)$",
        ),
        (
            "update_quantity",
            r"^(?:preview\s+)?(?:change|update|set)\s+(?:the\s+)?quote\s+(?:qty|quantity)\s+(?:on|for)\s+(?P<deal>.+?)\s+for\s+(?P<product>.+?)\s+to\s+(?P<quantity>.+)$",
        ),
        (
            "update_discount_pct",
            r"^(?:preview\s+)?(?:change|update|set)\s+(?:the\s+)?quote\s+(?:discount|discount percent|discount pct)\s+(?:on|for)\s+(?P<deal>.+?)\s+to\s+(?P<value>.+)$",
        ),
        (
            "update_term_months",
            r"^(?:preview\s+)?(?:change|update|set)\s+(?:the\s+)?quote\s+(?:term|term length|subscription term)\s+(?:on|for)\s+(?P<deal>.+?)\s+to\s+(?P<value>.+)$",
        ),
        (
            "update_payment_terms",
            r"^(?:preview\s+)?(?:change|update|set)\s+(?:the\s+)?quote\s+(?:payment terms|payment term|billing terms|billing term)\s+(?:on|for)\s+(?P<deal>.+?)\s+to\s+(?P<value>.+)$",
        ),
    )
    for operation, pattern in patterns:
        match = re.match(pattern, text, flags=re.IGNORECASE)
        if match is None:
            continue
        deal_reference = _strip_balanced_quotes(str(match.group("deal") or "").strip()).strip(" ?")
        if operation in {"add_product", "remove_product", "update_quantity"}:
            product_reference = _strip_balanced_quotes(str(match.group("product") or "").strip()).strip()
            quantity_value = (
                _strip_balanced_quotes(str(match.group("quantity") or "").strip()).strip()
                if "quantity" in match.groupdict()
                else ""
            )
            requested_value = _quote_preview_requested_value_payload(
                product_reference=product_reference,
                quantity=quantity_value or None,
            )
            if not deal_reference or not product_reference:
                return None
        else:
            requested_value = _strip_balanced_quotes(str(match.group("value") or "").strip()).strip()
        if not deal_reference or not requested_value:
            return None
        return {
            "operation": operation,
            "deal_reference": deal_reference,
            "requested_value": requested_value,
        }
    return None


def _quote_preview_requested_value_payload(
    *,
    product_reference: str,
    quantity: str | None = None,
) -> str:
    payload: dict[str, Any] = {"product_reference": str(product_reference or "").strip()}
    reference_type = _infer_quote_product_reference_type(product_reference)
    if reference_type:
        payload["product_reference_type"] = reference_type
    if quantity not in (None, ""):
        payload["quantity"] = str(quantity).strip()
    return json.dumps(payload, sort_keys=True)


def _infer_quote_product_reference_type(product_reference: str) -> str:
    value = str(product_reference or "").strip()
    if re.fullmatch(r"(?:01t|01u|01v)[a-zA-Z0-9]{12,15}", value, flags=re.IGNORECASE):
        return "product_id"
    if " " in value:
        return "product_name"
    return "product_code"


def _extract_deal_query(value: str) -> str | None:
    text = str(value or "").strip()
    text = re.sub(r"^(?:/dealdesk\s+)?", "", text, flags=re.IGNORECASE)
    patterns = (
        r"^(?:what is|what's)\s+the\s+quote\s+status\s+(?:on|for)\s+",
        r"^quote\s+status\s+(?:on|for)\s+",
        r"^quote\s+(?:on|for)\s+",
        r"^quote\s+",
        r"^(?:what is|what's)\s+the\s+approval\s+state\s+(?:on|for)\s+",
        r"^approval\s+state\s+(?:on|for)\s+",
        r"^who\s+still\s+needs\s+to\s+approve(?:\s+(?:on|for))?\s+",
        r"^who\s+needs\s+to\s+approve(?:\s+(?:on|for))?\s+",
        r"^approvals?\s+(?:on|for)\s+",
        r"^approvals?\s+",
        r"^is\s+there\s+a\s+stale\s+or\s+conflicting\s+quote\s+(?:on|for)\s+",
        r"^is\s+there\s+a\s+stale\s+quote\s+(?:on|for)\s+",
        r"^is\s+there\s+a\s+conflicting\s+quote\s+(?:on|for)\s+",
        r"^stale\s+or\s+conflicting\s+quote\s+(?:on|for)\s+",
        r"^stale\s+quote\s+(?:on|for)\s+",
        r"^conflicting\s+quote\s+(?:on|for)\s+",
        r"^(?:what is|what's)\s+blocking\s+close\s+on\s+",
        r"^blocking\s+close\s+on\s+",
        r"^where\s+is\s+",
        r"^deal\s+health\s+",
        r"^health\s+",
        r"^status\s+of\s+",
        r"^status\s+",
        r"^blockers?\s+for\s+",
        r"^blockers?\s+",
    )
    for pattern in patterns:
        text = re.sub(pattern, "", text, flags=re.IGNORECASE)
    text = re.sub(r"^\bthe\b\s+", "", text, flags=re.IGNORECASE)
    text = _strip_balanced_quotes(text).strip(" ?")
    return text or None


def _strip_balanced_quotes(value: str) -> str:
    text = str(value or "").strip()
    if len(text) >= 2 and text[0] == text[-1] and text[0] in {'"', "'"}:
        return text[1:-1].strip()
    return text


def _seller_fix_command_text(opportunity_id: str, field_name: str, org_alias: str | None) -> str:
    org_part = f" --org {org_alias}" if org_alias else ""
    return f"/dealdesk fix {opportunity_id} {field_name}=VALUE{org_part}"


def _seller_contact_command_text(opportunity_id: str, org_alias: str | None) -> str:
    org_part = f" --org {org_alias}" if org_alias else ""
    return f"/dealdesk contact {opportunity_id} contact@company.com role=Decision Maker{org_part}"


def _quote_record_headline(record: SellerQuoteStatusResultV1 | Any) -> str:
    if record is None:
        return "No supported quote linked"
    label = str(getattr(record, "label", "") or getattr(record, "quote_id", "")).strip()
    status = str(getattr(record, "status", "") or "Unknown").strip()
    return f"`{label}` ({_humanize_token(status)})"


def _quote_record_lines(record: Any | None) -> list[str]:
    if record is None:
        return []
    lines = [
        f"- *Label:* `{record.label}` (`{record.quote_id}`)",
        f"- *Status:* {_humanize_token(record.status)}",
    ]
    if record.amount is not None:
        lines.append(f"- *Amount:* `{record.amount:,.2f}`")
    if record.expiration_date:
        lines.append(f"- *Expires:* `{record.expiration_date}`")
    if record.last_modified_at:
        lines.append(f"- *Last Modified:* `{record.last_modified_at}`")
    if record.current_reason:
        lines.append(f"- *Why this quote:* {record.current_reason}")
    return lines


def _quote_approval_lines(summary: SellerQuoteStatusResultV1) -> list[str]:
    lines = [f"- *State:* {_humanize_token(summary.approval_state)}"]
    if summary.approval_submitted_at:
        lines.append(f"- *Submitted:* `{summary.approval_submitted_at}`")
    if summary.approval_completed_at:
        lines.append(f"- *Completed:* `{summary.approval_completed_at}`")
    if summary.pending_approvers:
        lines.append(
            "- *Pending approvers:* " + ", ".join(f"`{item.label}`" for item in summary.pending_approvers)
        )
    elif summary.expected_approvers:
        lines.append(
            "- *Expected approvers:* " + ", ".join(f"`{item.label}`" for item in summary.expected_approvers)
        )
    if summary.matched_approval_route_names:
        lines.append(
            "- *Matched routes:* " + ", ".join(f"`{item}`" for item in summary.matched_approval_route_names)
        )
    return lines


def _quote_signal_lines(summary: SellerQuoteStatusResultV1) -> list[str]:
    lines: list[str] = []
    if summary.stale_reasons:
        lines.extend(f"- *Stale:* {item}" for item in summary.stale_reasons)
    if summary.conflict_reasons:
        lines.extend(f"- *Conflict:* {item}" for item in summary.conflict_reasons)
    if not lines and summary.latest_quote_integrity_summary:
        lines.append(f"- *Latest close review:* {summary.latest_quote_integrity_summary}")
    return lines


def _quote_inventory_lines(records: list[Any]) -> list[str]:
    lines: list[str] = []
    for record in list(records or [])[:5]:
        detail = f"- `{record.label}`: {_humanize_token(record.status)}"
        if record.current_reason:
            detail += f" ({record.current_reason})"
        lines.append(detail)
    if len(records or []) > 5:
        lines.append(f"- ... and {len(records or []) - 5} more supported quote(s).")
    return lines


def _quote_coverage_lines(summary: SellerQuoteStatusResultV1) -> list[str]:
    lines: list[str] = []
    if summary.support_reason:
        lines.append(f"- {summary.support_reason}")
    lines.extend(f"- {item}" for item in list(summary.capability_gaps or [])[:4])
    if len(summary.capability_gaps or []) > 4:
        lines.append(f"- ... and {len(summary.capability_gaps or []) - 4} more gap(s).")
    return lines


def _quote_evidence_lines(evidence: list[Any], *, limit: int = 6) -> list[str]:
    lines: list[str] = []
    for item in list(evidence or [])[:limit]:
        label = str(getattr(item, "label", "") or getattr(item, "source_type", "Evidence")).strip()
        detail = str(getattr(item, "detail", "") or "").strip()
        if detail:
            lines.append(f"- *{label}:* {detail}")
        else:
            lines.append(f"- *{label}*")
    if len(evidence or []) > limit:
        lines.append(f"- ... and {len(evidence or []) - limit} more evidence row(s).")
    return lines


def _quote_preview_policy_lines(preview: SellerQuoteRevisionPreviewV1) -> list[str]:
    lines = [f"- *Policy state:* {_humanize_token(preview.preview_policy_state)}"]
    if preview.matched_approval_route_names:
        lines.append(
            "- *Matched routes:* " + ", ".join(f"`{item}`" for item in preview.matched_approval_route_names)
        )
    if preview.recommended_approval_roles:
        lines.append(
            "- *Recommended approvers:* " + ", ".join(f"`{item}`" for item in preview.recommended_approval_roles)
        )
    lines.extend(f"- {item}" for item in list(preview.preview_policy_reasons or [])[:4])
    if len(preview.preview_policy_reasons or []) > 4:
        lines.append(f"- ... and {len(preview.preview_policy_reasons or []) - 4} more signal(s).")
    return lines


def _quote_preview_coverage_lines(preview: SellerQuoteRevisionPreviewV1) -> list[str]:
    lines: list[str] = []
    if preview.support_reason:
        lines.append(f"- {preview.support_reason}")
    if preview.apply_support_reason:
        lines.append(f"- {preview.apply_support_reason}")
    lines.extend(f"- {item}" for item in list(preview.capability_gaps or [])[:4])
    if len(preview.capability_gaps or []) > 4:
        lines.append(f"- ... and {len(preview.capability_gaps or []) - 4} more gap(s).")
    return lines


def _quote_line_item_preview_lines(preview: Any) -> list[str]:
    lines = [
        f"- *Reference:* {_humanize_token(getattr(preview, 'product_reference_type', 'product_code'))} `{getattr(preview, 'product_reference_value', '')}`",
        f"- *Resolution:* {_humanize_token(getattr(preview, 'resolution_status', 'unknown'))}",
    ]
    resolution_reason = str(getattr(preview, "resolution_reason", "") or "").strip()
    if resolution_reason:
        lines.append(f"- *Why:* {resolution_reason}")
    current_lines = list(getattr(preview, "current_lines", []) or [])
    if current_lines:
        lines.extend(_quote_line_item_inventory_lines(current_lines, label="Current line"))
    proposed_line = getattr(preview, "proposed_line", None)
    if proposed_line is not None:
        lines.extend(_quote_line_item_inventory_lines([proposed_line], label="Proposed line"))
    diff_lines = [str(item).strip() for item in list(getattr(preview, "diff_lines", []) or []) if str(item).strip()]
    lines.extend(diff_lines[:4])
    if len(diff_lines) > 4:
        lines.append(f"- ... and {len(diff_lines) - 4} more diff line(s).")
    return lines


def _quote_line_item_inventory_lines(items: list[Any], *, label: str) -> list[str]:
    lines: list[str] = []
    for item in items[:2]:
        product_label = str(getattr(item, "product_name", "") or getattr(item, "product_code", "") or "Unknown product").strip()
        quantity_label = str(getattr(item, "quantity_display", "") or "Not available").strip()
        price_label = str(getattr(item, "net_price_display", "") or getattr(item, "unit_price_display", "") or "").strip()
        detail = f"- *{label}:* `{product_label}` x `{quantity_label}`"
        if price_label and price_label != "Not available":
            detail += f" | Price: `{price_label}`"
        lines.append(detail)
    if len(items) > 2:
        lines.append(f"- ... and {len(items) - 2} more matching line(s).")
    return lines


def _quote_apply_updated_status_lines(result: SellerQuoteStatusResultV1) -> list[str]:
    lines = [
        f"- *Support:* {_humanize_token(result.status)}",
        f"- *Approval:* {_humanize_token(result.approval_state)}",
    ]
    if result.selected_quote is not None:
        lines.append(
            f"- *Current quote:* `{result.selected_quote.label}` ({_humanize_token(result.selected_quote.status)})"
        )
    if result.pending_approvers:
        approvers = ", ".join(f"`{item.label}`" for item in result.pending_approvers[:4])
        lines.append(f"- *Pending approvers:* {approvers}")
        if len(result.pending_approvers) > 4:
            lines.append(f"- ... and {len(result.pending_approvers) - 4} more approver(s).")
    if result.conflict_reasons:
        lines.extend(f"- {item}" for item in list(result.conflict_reasons)[:2])
    elif result.stale_reasons:
        lines.extend(f"- {item}" for item in list(result.stale_reasons)[:2])
    elif result.latest_quote_integrity_summary:
        lines.append(f"- {result.latest_quote_integrity_summary}")
    return lines


__all__ = [
    "SlackDealDeskSellerCommand",
    "build_close_review_submission_blocks",
    "build_deal_lookup_blocks",
    "build_contact_role_result_blocks",
    "build_seller_contact_role_modal",
    "build_seller_field_fix_modal",
    "build_field_fix_result_blocks",
    "build_revops_close_review_alert_blocks",
    "build_seller_deal_health_blocks",
    "build_seller_quote_revision_approval_request_blocks",
    "build_seller_quote_revision_apply_result_blocks",
    "build_seller_quote_revision_preview_blocks",
    "build_seller_quote_status_blocks",
    "parse_seller_command",
    "seller_contact_modal_fallback_text",
    "seller_fix_modal_fallback_text",
    "seller_command_usage_text",
]
