"""Workspace hydrate polling: bootstrap hosting must settle on deploy status ``live``."""
from types import SimpleNamespace
from uuid import uuid4

from src.domain.builder.schemas import PreviewSummary
from src.domain.builder.service import (
    _apply_bootstrap_preview,
    _has_bootstrap_deploy_pending,
    _preview_candidate_url,
    _resolve_polling_complete,
)


def _deploy(
    status: str,
    *,
    bootstrap: bool = True,
    deploy_url: str | None = None,
    revision_id=None,
):
    return SimpleNamespace(
        status=status,
        deployment_metadata={"bootstrap_initial_hosting": True} if bootstrap else {},
        deploy_url=deploy_url,
        revision_id=revision_id or uuid4(),
    )


def _empty_preview() -> PreviewSummary:
    return PreviewSummary(
        active_preview_id=None,
        preview_status=None,
        preview_url=None,
        preview_source_revision_id=None,
        last_refreshed_at=None,
        preview_phase="empty",
    )


def test_live_bootstrap_deploy_is_not_pending():
    """Regression: ``live`` is the success status, not ``success``."""
    assert _has_bootstrap_deploy_pending([_deploy("live")]) is False
    assert _has_bootstrap_deploy_pending([_deploy("pending")]) is True
    assert _has_bootstrap_deploy_pending([_deploy("deploying")]) is True
    assert _has_bootstrap_deploy_pending([_deploy("failed")]) is False
    assert _has_bootstrap_deploy_pending([_deploy("rolled_back")]) is False
    assert _has_bootstrap_deploy_pending([_deploy("live", bootstrap=False)]) is False


def test_stale_w4p_live_hostname_is_corrected_to_preview_hostname():
    assert _preview_candidate_url(
        "https://proj-p5w04fsa.p2hsapp.com/",
        "p5w04fsa",
        "p2hsapp.com",
    ) == "https://prev-p5w04fsa.p2hsapp.com"


def test_provider_preview_url_is_preserved_when_not_stale_w4p_live_hostname():
    assert _preview_candidate_url(
        "https://branch.pages.dev/",
        "p5w04fsa",
        "p2hsapp.com",
    ) == "https://branch.pages.dev"


def test_polling_complete_when_bootstrap_hosting_is_live():
    assert _resolve_polling_complete(
        project_status="ready",
        latest_run_status=None,
        run_is_terminal=False,
        preview_phase="building",
        has_bootstrap_deploy_pending=False,
    ) is True


def test_polling_keeps_running_while_bootstrap_deploy_pending():
    assert _resolve_polling_complete(
        project_status="ready",
        latest_run_status=None,
        run_is_terminal=False,
        preview_phase="building",
        has_bootstrap_deploy_pending=True,
    ) is False


def test_polling_keeps_running_while_project_creating():
    assert _resolve_polling_complete(
        project_status="creating",
        latest_run_status=None,
        run_is_terminal=False,
        preview_phase="empty",
        has_bootstrap_deploy_pending=False,
    ) is False


def test_completed_with_l3_is_terminal_and_stops_polling():
    assert _resolve_polling_complete(
        project_status="ready",
        latest_run_status="completed_with_l3",
        run_is_terminal=True,
        preview_phase="ready",
        has_bootstrap_deploy_pending=False,
    ) is True


def test_live_bootstrap_surfaces_production_url_as_preview(monkeypatch):
    monkeypatch.setattr(
        "src.domain.builder.service.get_settings",
        lambda: SimpleNamespace(hosting_public_apex="p2hsapp.com"),
    )
    revision_id = uuid4()
    preview = _apply_bootstrap_preview(
        _empty_preview(),
        [_deploy("live", deploy_url="https://unused.example", revision_id=revision_id)],
        has_bootstrap_deploy_pending=False,
        latest_run_status=None,
        project_ref="p5w04fsa",
    )
    assert preview.preview_phase == "ready"
    assert preview.preview_url == "https://proj-p5w04fsa.p2hsapp.com"
    assert preview.preview_source_revision_id == revision_id


def test_live_bootstrap_heals_stale_provisioning_preview(monkeypatch):
    """A live W4P deploy must clear an older preview row stuck in provisioning."""
    monkeypatch.setattr(
        "src.domain.builder.service.get_settings",
        lambda: SimpleNamespace(hosting_public_apex="p2hsapp.com"),
    )
    revision_id = uuid4()
    stale_preview = _empty_preview().model_copy(
        update={
            "active_preview_id": uuid4(),
            "preview_status": "provisioning",
            "preview_source_revision_id": revision_id,
            "preview_phase": "building",
        }
    )
    out = _apply_bootstrap_preview(
        stale_preview,
        [_deploy("live", deploy_url="https://unused.example", revision_id=revision_id)],
        has_bootstrap_deploy_pending=False,
        latest_run_status="preview_refreshing",
        project_ref="p5w04fsa",
    )
    assert out.preview_phase == "ready"
    assert out.preview_url == "https://proj-p5w04fsa.p2hsapp.com"


def test_live_bootstrap_does_not_replace_newer_preview_revision(monkeypatch):
    monkeypatch.setattr(
        "src.domain.builder.service.get_settings",
        lambda: SimpleNamespace(hosting_public_apex="p2hsapp.com"),
    )
    out = _apply_bootstrap_preview(
        _empty_preview().model_copy(
            update={"preview_phase": "building", "preview_source_revision_id": uuid4()}
        ),
        [_deploy("live", revision_id=uuid4())],
        has_bootstrap_deploy_pending=False,
        latest_run_status="preview_refreshing",
        project_ref="p5w04fsa",
    )
    assert out.preview_phase == "building"


def test_pending_bootstrap_keeps_building_overlay():
    preview = _apply_bootstrap_preview(
        _empty_preview(),
        [_deploy("deploying")],
        has_bootstrap_deploy_pending=True,
        latest_run_status=None,
        project_ref="p5w04fsa",
    )
    assert preview.preview_phase == "building"
    assert preview.preview_url is None


def test_failed_bootstrap_surfaces_failed_preview():
    preview = _apply_bootstrap_preview(
        _empty_preview(),
        [_deploy("failed")],
        has_bootstrap_deploy_pending=False,
        latest_run_status=None,
        project_ref="p5w04fsa",
    )
    assert preview.preview_phase == "failed"
