"""E2E test: apps:rename — rename an app and verify everything moves.

Run with: pytest tests/e2e/test_apps_rename.py --backend real -v -s
"""

from __future__ import annotations

from typing import Any

import pytest

from kuberoku.exceptions import AppNotFoundError
from kuberoku.factory import KuberokuFactory
from tests.e2e.helpers import (
    cleanup_namespace_fixture,
    make_real_factory,
    skip_if_no_cluster,
    wait_for_pods_ready,
)


@pytest.fixture(scope="module")
def real_factory() -> KuberokuFactory:
    return make_real_factory("e2e-rename")


@pytest.fixture(scope="module", autouse=True)
def cleanup_namespace(real_factory: KuberokuFactory) -> Any:
    yield
    cleanup_namespace_fixture(real_factory)


def test_00_skip_if_no_cluster() -> None:
    """Skip the entire module if no cluster is available."""
    skip_if_no_cluster()


def test_01_create_and_deploy(real_factory: KuberokuFactory) -> None:
    """Create app and deploy nginx."""
    real_factory.apps.create("renametest")
    release = real_factory.deploy.deploy(
        "renametest",
        image="nginx:1.27-alpine",
        ports=[{"containerPort": 80, "protocol": "TCP"}],
        wait=False,
    )
    assert release.version == 1
    wait_for_pods_ready(real_factory, "renametest", expected=1)
    print(f"\n  Deployed renametest v{release.version}")


def test_02_config_set(real_factory: KuberokuFactory) -> None:
    """Set a config var so we can verify it survives rename."""
    real_factory.config.set("renametest", {"GREETING": "hello"})
    value, _ = real_factory.config.get("renametest", "GREETING")
    assert value == "hello"
    print("\n  Set GREETING=hello")


def test_03_rename_app(real_factory: KuberokuFactory) -> None:
    """Rename renametest → renamed."""
    steps: list[str] = []
    app = real_factory.apps.rename("renametest", "renamed", on_step=steps.append)
    assert app.name == "renamed"
    print(f"\n  Renamed to {app.name}")
    print(f"  Steps: {steps}")


def test_04_verify_old_gone(real_factory: KuberokuFactory) -> None:
    """info('renametest') should raise AppNotFoundError."""
    with pytest.raises(AppNotFoundError):
        real_factory.apps.info("renametest")
    print("\n  Old name is gone")


def test_05_verify_new_works(real_factory: KuberokuFactory) -> None:
    """info('renamed') should succeed."""
    app = real_factory.apps.info("renamed")
    assert app.name == "renamed"
    assert app.release_version >= 1
    print(f"\n  New app: {app.name}, release v{app.release_version}")


def test_06_verify_config_preserved(real_factory: KuberokuFactory) -> None:
    """Config vars should survive the rename."""
    value, source = real_factory.config.get("renamed", "GREETING")
    assert value == "hello"
    print(f"\n  GREETING={value} (source: {source})")


def test_07_cleanup(real_factory: KuberokuFactory) -> None:
    """Destroy the renamed app."""
    real_factory.apps.destroy("renamed")
    apps = real_factory.apps.list()
    assert not any(a.name == "renamed" for a in apps)
    print("\n  Cleaned up")
