"""Writable adopt changes stay in adopt mode. P2HS does not deploy their backend."""

from __future__ import annotations

from typing import Any

from src.domain.adopt.contract import PLATFORM_API_PREFIX, AdoptAttachment


def plan_backend_change(
    *,
    user_requested_migrate: bool,
    write_policy: str,
    cloud_has_capability: bool,
    change_kind: str = "gap",
) -> dict[str, Any]:
    if user_requested_migrate:
        return {
            "project_mode": "migrate",
            "action": "migrate_explicit",
            "p2hs_deploys_backend": False,
        }
    if cloud_has_capability:
        return {
            "project_mode": "adopt",
            "action": "use_platform_prefix",
            "path": PLATFORM_API_PREFIX,
            "pr": False,
            "p2hs_deploys_backend": False,
        }
    if write_policy == "frozen":
        return {
            "project_mode": "adopt",
            "action": "no_repo_change",
            "customer_hosted_attachment": "edge",
            "p2hs_deploys_backend": False,
        }
    if write_policy == "read_only":
        return {
            "project_mode": "adopt",
            "action": "inspect_only",
            "pr": False,
            "p2hs_deploys_backend": False,
        }
    if change_kind == "refinement":
        return {
            "project_mode": "adopt",
            "action": "refine_existing",
            "pr": True,
            "customer_ci_deploys": True,
            "p2hs_deploys_backend": False,
        }
    return {
        "project_mode": "adopt",
        "action": "gap_pr",
        "pr": True,
        "customer_ci_deploys": True,
        "p2hs_deploys_backend": False,
    }


def prompt_lines(adopt: dict[str, Any]) -> list[str]:
    if adopt.get("project_mode") != "adopt":
        return []
    lines = [
        "## Adopt mode",
        "This project is adopt, not migrate. Stay in adopt unless the user explicitly asks to move the whole application onto P2HS.",
        "Connecting a backend repository does not select migrate.",
        "P2HS hosting is w4p_static. Publish the static generate output. Do not reproduce Nitro or request-time SSR inside W4P.",
        "Generated code calls same-origin paths. Do not embed a customer origin, a secret, or a credential.",
        f"P2HS capability calls use {PLATFORM_API_PREFIX}. The dispatcher strips _p2hs before the canonical catalog path.",
        "customer_backend stays null. Existing API calls route only through the confirmed attachment.",
        "Do not copy inspection secrets into generated code, logs, or browser assets.",
    ]
    policy = adopt.get("backend_write_policy")
    if policy == "writable":
        lines.extend([
            "Writable backend changes are refinements of an existing function when that change is required.",
            f"When P2HS Cloud already provides the behavior, call it through {PLATFORM_API_PREFIX}. Do not add it to their backend.",
            "When Cloud does not provide it, open a pull request on their backend. Their CI/CD deploys that backend. P2HS does not deploy it.",
        ])
    elif policy == "frozen":
        lines.append(
            "The backend is frozen. Do not commit functions or /api/_p2hs into their repository. "
            "Customer-hosted attachment is the edge."
        )
    else:
        lines.append("The backend repository is read only. Do not commit to it.")
    return lines


def apply_adopt_contract(capabilities: dict[str, Any], attachment: AdoptAttachment) -> dict[str, Any]:
    """Attach the public adopt record and keep the generated app on Cloud."""
    updated = dict(capabilities)
    backend = dict(updated.get("backend") or {})
    if not attachment.legacy_customer_backend_required:
        backend["customer_backend"] = None
        backend["uses"] = backend.get("provider") or "p2hs_cloud"
    updated["backend"] = backend
    updated["adopt"] = attachment.edge_record()
    return updated
