"""Tests for ievo.core.startup — first-run checks."""

from __future__ import annotations

from pathlib import Path
from unittest.mock import MagicMock, patch

from ievo.core.global_config import load_global_config, set_config
from ievo.core.startup import ensure_startup
from ievo.core.telemetry import reset_sentry_state


def test_ensure_startup_first_run(tmp_path: Path) -> None:
    """First run: prompts both claude auth and telemetry."""
    reset_sentry_state()
    load_global_config(tmp_path)

    mock_prompt_auth = MagicMock(return_value="env")
    mock_prompt_telemetry = MagicMock(return_value=False)

    with (
        patch("ievo.core.startup.get_config", side_effect=[None, None]),
        patch("ievo.core.startup.init_sentry"),
        patch("ievo.core.claude_auth.prompt_claude_auth", mock_prompt_auth),
        patch("ievo.core.telemetry.prompt_telemetry", mock_prompt_telemetry),
    ):
        ensure_startup(tmp_path)

    mock_prompt_auth.assert_called_once_with(tmp_path)
    mock_prompt_telemetry.assert_called_once_with(tmp_path)


def test_ensure_startup_already_configured(tmp_path: Path) -> None:
    """Already configured: skips prompts, still inits sentry."""
    reset_sentry_state()
    load_global_config(tmp_path)
    set_config(tmp_path, "claude_auth", "env")
    set_config(tmp_path, "telemetry", False)

    mock_init_sentry = MagicMock()

    with patch("ievo.core.startup.init_sentry", mock_init_sentry):
        ensure_startup(tmp_path)

    mock_init_sentry.assert_called_once_with(tmp_path)


def test_ensure_startup_claude_configured_telemetry_not(tmp_path: Path) -> None:
    """Claude configured but telemetry not asked yet."""
    reset_sentry_state()
    load_global_config(tmp_path)
    set_config(tmp_path, "claude_auth", "cli")

    mock_prompt_telemetry = MagicMock(return_value=True)

    with (
        patch("ievo.core.startup.init_sentry"),
        patch("ievo.core.telemetry.prompt_telemetry", mock_prompt_telemetry),
    ):
        ensure_startup(tmp_path)

    mock_prompt_telemetry.assert_called_once_with(tmp_path)


def test_ensure_startup_telemetry_configured_claude_not(tmp_path: Path) -> None:
    """Telemetry configured but claude auth not."""
    reset_sentry_state()
    load_global_config(tmp_path)
    set_config(tmp_path, "telemetry", True)

    mock_prompt_auth = MagicMock(return_value=None)

    with (
        patch("ievo.core.startup.init_sentry"),
        patch("ievo.core.claude_auth.prompt_claude_auth", mock_prompt_auth),
    ):
        ensure_startup(tmp_path)

    mock_prompt_auth.assert_called_once_with(tmp_path)
