"""HubSpot native quotes adapter for the seller quote loop."""

from __future__ import annotations

from typing import Any

from .base import QuoteAdapter, QuoteAdapterSupportResult

HUBSPOT_SUPPORTED_HEADER_FIELDS = {
    "payment_terms": "hs_net_payment_terms",
    "expiration_date": "hs_expiration_date",
    "purchase_order_number": "hs_purchase_order_number",
}


def hubspot_field_preview_apply_support(*, field_preview: Any) -> tuple[bool, str]:
    semantic_key = str(getattr(field_preview, "semantic_key", "") or "").strip()
    field_name = str(getattr(field_preview, "field_name", "") or "").strip()
    expected_field_name = HUBSPOT_SUPPORTED_HEADER_FIELDS.get(semantic_key)
    if expected_field_name is None or field_name != expected_field_name:
        return (
            False,
            "Guided HubSpot apply currently supports `payment_terms` on `quotes.hs_net_payment_terms`, `expiration_date` on `quotes.hs_expiration_date`, and `purchase_order_number` on `quotes.hs_purchase_order_number` only.",
        )
    if bool(getattr(field_preview, "calculated", False)):
        return (
            False,
            "Guided HubSpot apply keeps calculated quote properties preview-only. This pilot requires a directly writable quote field.",
        )
    updateable = getattr(field_preview, "updateable", None)
    if updateable is False:
        return (
            False,
            f"Guided HubSpot apply cannot update `quotes.{field_name}` with the connected user in this portal.",
        )
    if updateable is not True:
        return (
            False,
            f"Guided HubSpot apply currently requires discovery to confirm that `quotes.{field_name}` is directly updateable in this portal.",
        )
    return True, ""


class HubSpotQuoteAdapter(QuoteAdapter):
    adapter_key = "hubspot_native_quotes"
    detected_engine = "hubspot_quotes"

    def seller_quote_support(self, *, environment_profile: Any) -> QuoteAdapterSupportResult:
        capability_profile = getattr(environment_profile, "adapter_capability_profile", None)
        supported_capabilities = set(getattr(capability_profile, "supported_capabilities", []) or [])
        if capability_profile is not None and "read_status" not in supported_capabilities:
            return QuoteAdapterSupportResult(
                status="unsupported",
                reason=(
                    "The detected HubSpot quote stack does not currently advertise read_status support for "
                    "seller quote status in Slack."
                ),
                capability_gaps=list(getattr(capability_profile, "notes", []) or []),
            )
        return QuoteAdapterSupportResult(status="supported")

    def live_approval_supported(self, *, environment_profile: Any) -> bool:
        del environment_profile
        return False

    def load_quote_records(
        self,
        *,
        opportunity_id: str,
        org_alias: str | None,
    ) -> list[Any]:
        from g_gremlin.dealdesk import service as service_mod

        return service_mod._load_hubspot_quote_records(
            opportunity_id=opportunity_id,
            org_alias=org_alias,
        )

    def load_quote_line_items(
        self,
        *,
        quote_id: str,
        org_alias: str | None,
        reference_type: str,
    ) -> list[Any]:
        del quote_id, org_alias, reference_type
        raise RuntimeError(
            "Guided HubSpot quote-line preview is not available in this pilot. Seller-safe support is limited to draft quote header updates."
        )

    def quote_line_item_object_name(self) -> str:
        return "quote_line_items"

    def preview_apply_support(self, *, preview: Any) -> tuple[bool, str]:
        if getattr(preview, "line_item_preview", None) is not None:
            return (
                False,
                "Guided HubSpot apply currently supports draft quote header updates only. Line-item changes remain preview-only in this pilot.",
            )
        selected_quote = getattr(preview, "selected_quote", None)
        field_preview = getattr(preview, "field_preview", None)
        if selected_quote is None or field_preview is None:
            return (
                False,
                "Guided HubSpot apply currently requires a selected quote and a resolved quote-header field preview.",
            )
        quote_object_name = str(getattr(selected_quote, "object_name", "") or "").strip()
        field_object_name = str(getattr(field_preview, "object_name", "") or "").strip()
        if quote_object_name != "quotes" or field_object_name != "quotes":
            return (
                False,
                "Guided HubSpot apply currently supports native `quotes` header updates only.",
            )
        quote_status = str(getattr(selected_quote, "status", "") or "").strip().upper()
        if quote_status != "DRAFT":
            return (
                False,
                "Guided HubSpot apply currently requires a draft quote. Published, accepted, expired, and archived quotes remain preview-only in this pilot.",
            )
        return hubspot_field_preview_apply_support(field_preview=field_preview)

    def build_quote_revision_plan(
        self,
        *,
        preview: Any,
        org_alias: str | None,
        run_id: str | None = None,
    ) -> Any:
        from g_gremlin.dealdesk import service as service_mod

        return service_mod._build_hubspot_quote_revision_plan(
            preview=preview,
            org_alias=org_alias,
            run_id=run_id,
        )

__all__ = [
    "HUBSPOT_SUPPORTED_HEADER_FIELDS",
    "HubSpotQuoteAdapter",
    "hubspot_field_preview_apply_support",
]
