"""Versioned capability descriptions; no credentials or authorization grants."""

CATALOG_VERSION = "2"
BOILERPLATES = {
    "html": "Static website or landing page; no server-side BFF.",
    "react_app": "React web application with platform adapter conventions.",
    "nuxt_app": "Nuxt SSR web application with server-side BFF routes; suitable for SaaS.",
    "shopify_app": "Shopify application integration; requires Shopify installation.",
    "ai_assist_shopify": "Work on a connected Shopify store through the companion integration.",
    "ai_assist_wordpress": "Work on a connected WordPress site through the companion integration.",
}
CLOUD_CAPABILITIES = {
    "auth": "Platform authentication, sessions and staff roles; do not create local identities.",
    "records": (
        "Cloud entities, fields, relations and tenant-scoped records; declare "
        "via p2hs/provision.json."
    ),
    "storage": "Platform storage buckets and uploads; declare buckets via provisioning.",
    "functions": "Catalog functions, event/webhook/schedule triggers via p2hs/functions.json.",
    "feature_packs": "Reusable backend feature packs via p2hs/feature-packs.json.",
    "connectors": (
        "Provider integrations require Core-approved capabilities and configured credentials."
    ),
    "realtime": "Platform realtime delivery where enabled.",
    "ai": "Controlled AI capabilities where enabled; no provider credentials in the browser.",
    "subscriptions": (
        "Generated-app payment integration requires configured Stripe "
        "credentials and webhooks; never reuse P2HS workspace billing."
    ),
}
CONVERSATION_WINDOW = 16
MODEL_FACING_KEYS = (
    "catalog_version",
    "latest_input",
    "discovery_state",
    "conversation",
    "project_context",
    "platform_context",
    "environment",
)


def model_facing_discovery_payload(payload: dict) -> dict:
    """Omit worker compatibility aliases duplicated for starter-selection checks."""
    return {key: payload[key] for key in MODEL_FACING_KEYS if key in payload}


def build_discovery_payload(
    project_type, source_kind, state, templates, *, environment_status: str = "preparing"
):
    supported = (
        ["html", "react_app", "nuxt_app"]
        if project_type in {"html", "react_app", "nuxt_app"}
        else [project_type]
    )
    messages = state.get("messages") or []
    result = state.get("result") or {}
    return {
        "catalog_version": CATALOG_VERSION,
        "latest_input": state.get("latest_input")
        or (
            {"type": "message", "content": messages[-1]["content"]}
            if messages and messages[-1]["role"] == "user"
            else {"type": "message", "content": state.get("initial_prompt", "")}
        ),
        "discovery_state": {
            "revision": state.get("version", 0),
            "status": state.get("status", "pending"),
            "spec": result.get("spec"),
            "previous_decision": result.get("decision"),
            "core_blockers": state.get("core_blockers") or [],
        },
        "conversation": messages[-CONVERSATION_WINDOW:],
        "project_context": {
            "imported_project": source_kind != "generated",
            "locked_type": project_type if source_kind != "generated" else state.get("locked_type"),
            "has_attachments": bool(state.get("attachment_ids")),
        },
        "platform_context": {
            "boilerplates": {key: BOILERPLATES[key] for key in supported},
            "cloud_capabilities": CLOUD_CAPABILITIES,
            "templates": [
                {
                    "ref": item.ref,
                    "name": item.name,
                    "description": (item.description or "")[:1500],
                    "framework": item.framework,
                    "tags": item.tags or [],
                    "auto_selectable": bool((item.description or "").strip() or item.tags),
                }
                for item in templates
                if item.framework in supported
            ][:40],
        },
        "environment": {"status": environment_status},
        # Compatibility aliases used by starter-selection checks in the worker.
        "imported_project": source_kind != "generated",
        "locked_type": project_type if source_kind != "generated" else state.get("locked_type"),
        "boilerplates": {key: BOILERPLATES[key] for key in supported},
        "cloud": CLOUD_CAPABILITIES,
        "templates": [
            {
                "ref": item.ref,
                "name": item.name,
                "description": (item.description or "")[:1500],
                "framework": item.framework,
                "tags": item.tags or [],
                "auto_selectable": bool((item.description or "").strip() or item.tags),
            }
            for item in templates
            if item.framework in supported
        ][:40],
        "messages": messages,
        "has_attachments": bool(state.get("attachment_ids")),
    }
