"""Tests for appxen stats command."""

from unittest.mock import MagicMock, patch

from typer.testing import CliRunner

from appxen_cli.main import app


class TestStats:

    @patch("appxen_cli.main.get_client")
    def test_stats_displays_panel(self, mock_get_client):
        """Stats shows source/chunk counts."""
        mock_client = MagicMock()
        mock_client.stats.return_value = {
            "source_count": 10,
            "chunk_count": 200,
            "storage_bytes": 5242880,
        }
        mock_get_client.return_value = mock_client

        runner = CliRunner()
        result = runner.invoke(app, ["stats"])
        assert result.exit_code == 0
        assert "10" in result.output
        assert "200" in result.output

    @patch("appxen_cli.main.get_client")
    def test_stats_json(self, mock_get_client):
        """Stats with --json outputs raw JSON."""
        mock_client = MagicMock()
        mock_client.stats.return_value = {"source_count": 3, "chunk_count": 50}
        mock_get_client.return_value = mock_client

        runner = CliRunner()
        result = runner.invoke(app, ["stats", "--json"])
        assert result.exit_code == 0
        assert '"source_count"' in result.output

    @patch("appxen_cli.main.get_client")
    def test_stats_error(self, mock_get_client):
        """Stats shows error when API fails."""
        mock_client = MagicMock()
        mock_client.stats.side_effect = Exception("Connection refused")
        mock_get_client.return_value = mock_client

        runner = CliRunner()
        result = runner.invoke(app, ["stats"])
        assert result.exit_code == 1
        assert "Failed" in result.output
