from __future__ import annotations

import sys
from pathlib import Path
from unittest.mock import patch

import pytest

from amplitude_ai.cli.doctor import run_doctor
from amplitude_ai.cli.main import _get_guide_path, _print_guide


class TestPrintGuide:
    """Tests for the --print-guide CLI flag and related helpers."""

    def test_get_guide_path_resolves_dev_layout(self) -> None:
        path = _get_guide_path()
        assert Path(path).exists()
        assert path.endswith("amplitude-ai.md")

    def test_print_guide_writes_to_stdout(self, capsys: pytest.CaptureFixture[str]) -> None:
        _print_guide()
        captured = capsys.readouterr()
        assert "amplitude-ai" in captured.out.lower()
        assert len(captured.out) > 100

    def test_print_guide_exits_on_missing_file(self, monkeypatch: pytest.MonkeyPatch) -> None:
        monkeypatch.setattr(
            "amplitude_ai.cli.main._get_guide_path",
            lambda: "/nonexistent/path/amplitude-ai.md",
        )
        with pytest.raises(SystemExit, match="1"):
            _print_guide()


def test_run_doctor_reports_missing_api_key(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.delenv("AMPLITUDE_AI_API_KEY", raising=False)
    result = run_doctor(tmp_path)
    assert result["ok"] is False
    assert any(check["name"] == "env.AMPLITUDE_AI_API_KEY" for check in result["checks"])
    assert any(
        check["name"] == "mock_event_delivery" and check["ok"] is True
        for check in result["checks"]
    )
    assert any(
        check["name"] == "mock_flush_path" and check["ok"] is True
        for check in result["checks"]
    )


def test_run_doctor_can_skip_mock_check(tmp_path: Path) -> None:
    result = run_doctor(tmp_path, include_mock_check=False)
    assert not any(check["name"] == "mock_event_delivery" for check in result["checks"])
    assert not any(check["name"] == "mock_flush_path" for check in result["checks"])
