"""Who is allowed to start a generated-app build.

One git push starts deploy.yml. Core workers observe that run and activate
routing. A workflow_dispatch is only a delayed backfill when no push and no
completed workflow were seen.
"""

from __future__ import annotations

DEPLOY_WORKFLOW_NAMES = (
    "Deploy to Cloudflare Pages",
    "Deploy to Cloudflare W4P",
)

_WEBHOOK_TRIGGER = "workflow_run_webhook"


def is_generated_app_deploy_workflow(name: str) -> bool:
    text = name or ""
    return any(token in text for token in DEPLOY_WORKFLOW_NAMES)


def should_promote_production(metadata: dict | None) -> bool:
    """False when main was already pushed or CI already finished."""
    meta = metadata or {}
    if meta.get("triggered_by_merge"):
        return False
    if meta.get("triggered_by") == _WEBHOOK_TRIGGER:
        return False
    return True


def ci_already_started(metadata: dict | None, *, ci_just_pushed: bool) -> bool:
    meta = metadata or {}
    return bool(
        ci_just_pushed
        or meta.get("triggered_by_merge")
        or meta.get("triggered_by") == _WEBHOOK_TRIGGER
    )


def should_dispatch_workflow(
    metadata: dict | None,
    *,
    job_try: int,
    ci_just_pushed: bool,
) -> bool:
    """Dispatch only when this attempt did not already start CI and none was observed."""
    meta = metadata or {}
    if meta.get("triggered_by") == _WEBHOOK_TRIGGER:
        return False
    if meta.get("triggered_by_merge") or ci_just_pushed:
        return False
    return job_try >= 2
