"""Tests for module UX enhancements (Phase 4)."""

from __future__ import annotations

import json

from typer.testing import CliRunner

from ilum.cli.main import app


class TestModuleListSearch:
    def test_search_by_name(self) -> None:
        runner = CliRunner()
        result = runner.invoke(app, ["module", "list", "--search", "sql"])
        assert result.exit_code == 0
        assert "sql" in result.output.lower()

    def test_search_by_description(self) -> None:
        runner = CliRunner()
        result = runner.invoke(app, ["module", "list", "--search", "notebook"])
        assert result.exit_code == 0

    def test_search_no_results(self) -> None:
        runner = CliRunner()
        result = runner.invoke(app, ["module", "list", "--search", "zzz-nonexistent"])
        assert result.exit_code == 0
        # Should show empty table or no rows

    def test_search_with_json_output(self) -> None:
        runner = CliRunner()
        result = runner.invoke(app, ["--output", "json", "module", "list", "--search", "core"])
        assert result.exit_code == 0
        data = json.loads(result.output)
        assert isinstance(data, list)
        assert any("core" in m["name"] for m in data)


class TestModuleTree:
    def test_tree_core(self) -> None:
        runner = CliRunner()
        result = runner.invoke(app, ["module", "tree", "core"])
        assert result.exit_code == 0
        assert "core" in result.output

    def test_tree_with_dependencies(self) -> None:
        runner = CliRunner()
        # trino requires hive-metastore and postgresql
        result = runner.invoke(app, ["module", "tree", "trino"])
        assert result.exit_code == 0
        assert "trino" in result.output

    def test_tree_unknown_module(self) -> None:
        runner = CliRunner()
        result = runner.invoke(app, ["module", "tree", "nonexistent"])
        assert result.exit_code == 1

    def test_tree_shows_resource_estimates(self) -> None:
        runner = CliRunner()
        result = runner.invoke(app, ["module", "tree", "core"])
        assert result.exit_code == 0
        # Should show resource estimates
        assert "GiB" in result.output or "MiB" in result.output or "CPU" in result.output


class TestModuleShowResources:
    def test_show_includes_resource_estimate(self) -> None:
        runner = CliRunner()
        result = runner.invoke(app, ["module", "show", "core"])
        assert result.exit_code == 0
        assert (
            "Resource estimate" in result.output or "GiB" in result.output or "CPU" in result.output
        )

    def test_show_json_includes_resources(self) -> None:
        runner = CliRunner()
        result = runner.invoke(app, ["--output", "json", "module", "show", "core"])
        assert result.exit_code == 0
        data = json.loads(result.output)
        assert data["name"] == "core"
