"""Deterministic routing for Deal Desk quote adapters."""

from __future__ import annotations

from typing import Any

from .base import QuoteAdapter, QuoteAdapterSupportResult
from .salesforce_cpq import SalesforceCpqQuoteAdapter
from .salesforce_standard import SalesforceStandardQuoteAdapter


_ADAPTERS: dict[str, QuoteAdapter] = {
    "salesforce_cpq": SalesforceCpqQuoteAdapter(),
    "standard_quotes": SalesforceStandardQuoteAdapter(),
}


def resolve_quote_adapter(*, detected_engine: str | None) -> QuoteAdapter | None:
    normalized_engine = str(detected_engine or "").strip().lower()
    return _ADAPTERS.get(normalized_engine)


def resolve_quote_adapter_for_environment(*, environment_profile: Any) -> QuoteAdapter | None:
    return resolve_quote_adapter(detected_engine=getattr(environment_profile, "detected_engine", None))


def seller_quote_support(*, environment_profile: Any) -> QuoteAdapterSupportResult:
    detected_engine = str(getattr(environment_profile, "detected_engine", "") or "").strip().lower()
    if detected_engine == "mixed":
        return QuoteAdapterSupportResult(
            status="ambiguous",
            reason=(
                "Multiple quote engines were detected in this org, so Gremlin cannot safely choose a seller quote source of truth yet."
            ),
            capability_gaps=list(getattr(environment_profile, "unsupported_reasons", []) or []),
        )
    adapter = resolve_quote_adapter(detected_engine=detected_engine)
    if adapter is None:
        engine_label = detected_engine.replace("_", " ") or "unknown"
        return QuoteAdapterSupportResult(
            status="unsupported",
            reason=(
                "Seller-facing quote status is currently limited to Salesforce Standard Quotes and "
                f"Salesforce CPQ. Detected engine: {engine_label}."
            ),
            capability_gaps=list(getattr(environment_profile, "unsupported_reasons", []) or []),
        )
    return adapter.seller_quote_support(environment_profile=environment_profile)


__all__ = [
    "resolve_quote_adapter",
    "resolve_quote_adapter_for_environment",
    "seller_quote_support",
]
