"""Smoke tests for reddit-mcp — config, CLI routing, and tool schema validation."""

from __future__ import annotations

import json
import subprocess
import sys


class TestCLIRouting:
    """CLI commands execute without crash."""

    def test_version(self) -> None:
        result = subprocess.run(
            [sys.executable, "-m", "reddit_mcp.cli", "version"],
            capture_output=True,
            text=True,
            timeout=10,
        )
        assert result.returncode == 0
        # Should print a version string
        assert result.stdout.strip()

    def test_help(self) -> None:
        result = subprocess.run(
            [sys.executable, "-m", "reddit_mcp.cli"],
            capture_output=True,
            text=True,
            timeout=10,
        )
        assert result.returncode == 0
        assert "reddit-mcp" in result.stdout
        assert "reddit-mcp uninstall" in result.stdout
        assert 'uvx --from 5mghost-rover reddit-mcp serve' in result.stdout

    def test_unknown_command_shows_help(self) -> None:
        result = subprocess.run(
            [sys.executable, "-m", "reddit_mcp.cli", "nonexistent"],
            capture_output=True,
            text=True,
            timeout=10,
        )
        # Unknown command falls through to help (exit 0 is current behavior)
        assert "reddit-mcp" in result.stdout

    def test_help_flag_does_not_execute_uninstall(self) -> None:
        result = subprocess.run(
            [sys.executable, "-m", "reddit_mcp.cli", "uninstall", "--help"],
            capture_output=True,
            text=True,
            timeout=10,
        )
        assert result.returncode == 0
        assert "reddit-mcp uninstall" in result.stdout
        assert "Removing MCP client registrations" not in result.stdout


class TestConfig:
    """Config module sanity checks."""

    def test_auth_url_is_https(self) -> None:
        from fivemghost_shared_client.config_helpers import AUTH_URL

        assert AUTH_URL.startswith("https://")

    def test_config_dir_is_under_home(self) -> None:
        from reddit_mcp.config import CONFIG_DIR
        import os

        assert str(CONFIG_DIR).startswith(os.path.expanduser("~"))


class TestTokenPriority:
    """Token priority: ENV > PAT > JWT."""

    def test_env_var_takes_precedence(self, monkeypatch: object) -> None:
        import pytest

        monkeypatch = pytest.importorskip("pytest").MonkeyPatch()
        monkeypatch.setenv("REDDIT_MCP_TOKEN", "test-token-123")

        import asyncio

        from fivemghost_shared_client.config_helpers import AUTH_URL, SHARED_AUTH_JSON
        from fivemghost_shared_client import TokenManager

        tm = TokenManager(AUTH_URL, auth_json_path=SHARED_AUTH_JSON, env_token_name="REDDIT_MCP_TOKEN")
        token = asyncio.run(tm.get_valid_token())
        assert token == "test-token-123"
        monkeypatch.undo()


class TestOpenClawHelpers:
    def test_remove_openclaw_entry_preserves_other_servers(self) -> None:
        from fivemghost_shared_client.registration.openclaw import remove_openclaw_config_entry_text

        current = json.dumps(
            {
                "servers": {
                    "reddit-mcp": {"transport": "stdio", "command": "python3", "args": ["launcher.py", "serve"]},
                    "yt-mcp": {"transport": "stdio", "command": "node", "args": ["launcher.js", "serve"]},
                }
            }
        )

        result = remove_openclaw_config_entry_text(current, "reddit-mcp")

        assert result["changed"] is True
        assert result["next_text"] is not None
        next_config = json.loads(result["next_text"])
        assert "reddit-mcp" not in next_config["servers"]
        assert "yt-mcp" in next_config["servers"]
