"""Which hosting provider a project's deploys use.

New projects (created at or after the platform cutoff) use Workers for Platforms static assets.
Existing projects keep the global ``hosting_provider`` until their planned cutover.
"""

from __future__ import annotations

from typing import Any

from src.domain.hosting.deploy_target import project_is_platform

W4P_STATIC = "cloudflare_w4p_static"


def project_hosting_provider(
    project_created_at,
    settings: Any,
    *,
    primary_hosting_provider: str | None = None,
    assume_unassigned_w4p: bool = False,
    has_successful_pages_deployment: bool | None = None,
) -> str:
    explicit = (primary_hosting_provider or "").strip().lower()
    if explicit in {W4P_STATIC, "cloudflare_w4p", "w4p"}:
        return W4P_STATIC
    if explicit in {"cloudflare_pages", "cloudflare"}:
        # An explicitly Pages-marked project that has never successfully
        # deployed to Pages is still eligible for the automatic legacy
        # migration rule. Once Pages has a live deployment, keep it on Pages
        # unless an operator explicitly changes the provider.
        if assume_unassigned_w4p and has_successful_pages_deployment is False:
            return W4P_STATIC
        return "cloudflare_pages"
    if explicit:
        # A persisted selection wins over the platform cutoff and the global default.
        return explicit
    if project_is_platform(project_created_at, settings):
        return W4P_STATIC
    if assume_unassigned_w4p and not explicit and has_successful_pages_deployment is not True:
        return W4P_STATIC
    return (settings.hosting_provider or "").strip() or "cloudflare_pages"


def is_pages_project_limit_error(message: str | None) -> bool:
    text = (message or "").lower()
    return "8000027" in text or "reached the limit of projects" in text
