"""Salesforce CPQ / Revenue Cloud adapter for the seller quote loop."""

from __future__ import annotations

from typing import Any

from .base import QuoteAdapter, QuoteAdapterSupportResult


def salesforce_cpq_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()
    if semantic_key == "term_months":
        return (
            False,
            "Guided Salesforce CPQ apply keeps subscription-term updates preview-only because live-org validation showed calculator-driven quote total changes beyond the direct field diff. This slice needs calculator-aware postchecks before Slack apply is enabled.",
        )
    if semantic_key != "payment_terms":
        return (
            False,
            "Guided Salesforce CPQ apply currently supports non-calculator payment-terms header updates only. Calculator-backed discount and term changes remain preview-only.",
        )
    if bool(getattr(field_preview, "calculated", False)):
        return (
            False,
            f"Guided Salesforce CPQ apply keeps calculated or formula-backed fields preview-only. `{field_name}` needs a non-calculator fallback before Slack apply is enabled.",
        )
    updateable = getattr(field_preview, "updateable", None)
    if updateable is False:
        return (
            False,
            f"Guided Salesforce CPQ apply cannot update `{field_name}` with the connected user in this org. This field stays preview-only in this slice.",
        )
    if updateable is not True:
        return (
            False,
            f"Guided Salesforce CPQ apply currently requires discovery to confirm that `{field_name}` is directly updateable on SBQQ__Quote__c. This field stays preview-only in this org.",
        )
    return True, ""


class SalesforceCpqQuoteAdapter(QuoteAdapter):
    adapter_key = "salesforce_cpq"
    detected_engine = "salesforce_cpq"

    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 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:
        return bool(getattr(environment_profile, "approval_objects", None))

    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_salesforce_cpq_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]:
        from g_gremlin.dealdesk import service as service_mod

        return service_mod._load_salesforce_cpq_quote_line_items(
            quote_id=quote_id,
            org_alias=org_alias,
            reference_type=reference_type,
        )

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

    def preview_apply_support(self, *, preview: Any) -> tuple[bool, str]:
        if getattr(preview, "line_item_preview", None) is not None:
            return (
                False,
                "Guided line-item apply currently supports Salesforce Standard Quotes only. This stack remains preview-only.",
            )
        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 Salesforce CPQ apply currently requires a selected primary quote and a resolved SBQQ__Quote__c 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 != "SBQQ__Quote__c" or field_object_name != "SBQQ__Quote__c":
            return (
                False,
                "Guided Salesforce CPQ apply currently supports SBQQ__Quote__c header updates only. Other quote shapes remain preview-only.",
            )
        if not bool(getattr(selected_quote, "is_primary", False)):
            return (
                False,
                "Guided Salesforce CPQ apply currently requires the selected primary quote. This org shape stays preview-only until RevOps confirms a stable current-quote rule.",
            )
        if bool(getattr(selected_quote, "is_ordered", False)):
            return (
                False,
                "Guided Salesforce CPQ apply does not mutate ordered quotes. This quote stays preview-only in this slice.",
            )
        field_supported, field_reason = salesforce_cpq_field_preview_apply_support(field_preview=field_preview)
        if not field_supported:
            return field_supported, field_reason

        from g_gremlin.dealdesk import service as service_mod

        verification_supported, verification_reason, _requirements = (
            service_mod._salesforce_cpq_payment_terms_postcheck_requirements(
                org_alias=getattr(preview, "org_alias", None)
            )
        )
        if not verification_supported:
            return False, verification_reason
        return True, ""

    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_salesforce_cpq_quote_revision_plan(
            preview=preview,
            org_alias=org_alias,
            run_id=run_id,
        )


__all__ = ["SalesforceCpqQuoteAdapter", "salesforce_cpq_field_preview_apply_support"]
