"""Core policy projection for manifest assembly and codegen workers."""

from src.integrations.platform_ports import CATALOG_VERSION, entitled_ports


async def project_port_context(db, project) -> dict:
    from src.domain.codegen.client_surface import (
        CLIENT_OPERATION_REGISTRY,
        resolve_client_surface,
    )
    from src.domain.codegen.runtime_contract import resolve_runtime_contract
    from src.domain.projects.repository import ProjectSettingsRepository
    from src.domain.workspaces.models import Workspace

    row = await ProjectSettingsRepository(db).get_or_create(project.id)
    workspace = await db.get(Workspace, project.workspace_id)
    plan = getattr(workspace, "selected_plan_slug", None) or "free"
    runtime_contract = await resolve_runtime_contract(db, project)
    ports = entitled_ports(row.settings or {}, plan)
    runtime_contract_payload = runtime_contract.model_dump()
    # The port catalog is entitlement-wide, while the runtime contract is
    # project-specific.  Do not expose password operations in a passwordless
    # project's generated client surface merely because those ports exist in
    # the catalog.  Otherwise older/admin UI composition can resurrect
    # password setup/reset controls even when auth.password is false.
    operations = list(CLIENT_OPERATION_REGISTRY)
    auth = (runtime_contract_payload.get("capabilities") or {}).get("auth") or {}
    if auth.get("password") is False:
        operations = [
            operation
            for operation in operations
            if operation
            not in {
                "auth.password_sign_in",
                "auth.password_reset_request",
                "auth.password_reset_complete",
            }
        ]
    runtime_contract_payload["client_surface"] = resolve_client_surface(
        {"ports": ports}, operations
    )
    return {
        "ports": ports,
        "project_id": str(project.id),
        "workspace_id": str(project.workspace_id),
        "client_id": f"cli_{project.project_ref or project.id}",
        "catalog_version": CATALOG_VERSION,
        "runtime_contract": runtime_contract_payload,
    }
