"""E2E: plugin system — list, search, CLI output.

Verifies that the plugin system works end-to-end with real
importlib.metadata entry_points scanning and PyPI API calls.

Note: We cannot install/uninstall real packages in CI, so these
tests focus on list (empty), search (nonexistent), and CLI output.

Run with: pytest tests/e2e/test_plugins.py -v -s
"""

from __future__ import annotations

from typing import Any

import pytest
from click.testing import CliRunner

from kuberoku.cli.plugins import plugins as plugins_group
from kuberoku.factory import KuberokuFactory
from tests.e2e.helpers import (
    cleanup_namespace_fixture,
    make_real_factory,
    skip_if_no_cluster,
)


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


@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(real_factory: KuberokuFactory) -> None:
    skip_if_no_cluster()


def test_01_plugins_list_empty(real_factory: KuberokuFactory) -> None:
    """No kuberoku plugins installed in test environment."""
    plugins = real_factory.plugins.list_installed()
    # In a clean test env, no kuberoku-* plugins should be installed
    assert isinstance(plugins, tuple)
    print(f"\n  Installed plugins: {len(plugins)}")
    for p in plugins:
        print(f"    {p.name} ({p.package} {p.version})")


def test_02_plugins_search_nonexistent(real_factory: KuberokuFactory) -> None:
    """Searching for a nonexistent plugin returns empty."""
    results = real_factory.plugins.search("zzz-no-such-plugin-e2e-test")
    assert isinstance(results, tuple)
    assert len(results) == 0
    print(f"\n  Search 'zzz-no-such-plugin-e2e-test': {len(results)} results")


def test_03_cli_plugins_list(real_factory: KuberokuFactory) -> None:
    """CLI: plugins → 'No plugins' or table output."""
    runner = CliRunner()
    result = runner.invoke(
        plugins_group,
        [],
        obj={"factory": real_factory},
    )
    assert result.exit_code == 0, f"CLI failed: {result.output}"
    # Either "No plugins" or a table with plugin info
    assert "No plugins" in result.output or "name" in result.output.lower()
    print(f"\n  CLI plugins list:\n{result.output}")


def test_04_cli_plugins_search(real_factory: KuberokuFactory) -> None:
    """CLI: plugins search zzz-no-such → exit_code 0."""
    runner = CliRunner()
    result = runner.invoke(
        plugins_group,
        ["search", "zzz-no-such-plugin-e2e-test"],
        obj={"factory": real_factory},
    )
    assert result.exit_code == 0, f"CLI failed: {result.output}"
    assert "No plugins found" in result.output
    print(f"\n  CLI plugins search:\n{result.output}")
