"""Tests for PsService.list_dynos (ps command)."""

from __future__ import annotations

from kuberoku.factory import KuberokuFactory
from tests.ps.conftest import create_test_pod as _create_pod


def test_list_empty(deployed_factory: KuberokuFactory) -> None:
    dynos = deployed_factory.ps.list_dynos("myapp")
    assert dynos == []


def test_list_with_pods(deployed_factory: KuberokuFactory) -> None:
    _create_pod(deployed_factory, "myapp", "web", "web-pod-1")
    _create_pod(deployed_factory, "myapp", "web", "web-pod-2")
    dynos = deployed_factory.ps.list_dynos("myapp")
    assert len(dynos) == 2
    assert dynos[0].name == "web.1"
    assert dynos[1].name == "web.2"


def test_dyno_numbering_by_start_time(deployed_factory: KuberokuFactory) -> None:
    _create_pod(deployed_factory, "myapp", "web", "web-pod-old", start_time="2024-01-01T00:00:00Z")
    _create_pod(deployed_factory, "myapp", "web", "web-pod-new", start_time="2024-01-02T00:00:00Z")
    dynos = deployed_factory.ps.list_dynos("myapp")
    assert dynos[0].name == "web.1"
    assert dynos[1].name == "web.2"


def test_dyno_state_mapping(deployed_factory: KuberokuFactory) -> None:
    _create_pod(deployed_factory, "myapp", "web", "web-1", phase="Running")
    _create_pod(deployed_factory, "myapp", "web", "web-2", phase="Pending")
    _create_pod(deployed_factory, "myapp", "web", "web-3", phase="Failed")
    dynos = deployed_factory.ps.list_dynos("myapp")
    states = {d.name: d.state for d in dynos}
    assert states["web.1"] == "up"
    assert states["web.2"] == "starting"
    assert states["web.3"] == "crashed"


def test_dyno_has_image(deployed_factory: KuberokuFactory) -> None:
    _create_pod(deployed_factory, "myapp", "web", "web-1")
    dynos = deployed_factory.ps.list_dynos("myapp")
    assert dynos[0].image == "myapp:v1"


def test_dyno_has_process_type(deployed_factory: KuberokuFactory) -> None:
    _create_pod(deployed_factory, "myapp", "web", "web-1")
    dynos = deployed_factory.ps.list_dynos("myapp")
    assert dynos[0].process_type == "web"
    assert dynos[0].app == "myapp"
