from __future__ import annotations

from typer.testing import CliRunner

from worai import cli as root_cli
from worai.update import UpdateCheckResult


def test_self_update_prints_available_update_without_running(monkeypatch) -> None:
    def _stub_check(*_args, **_kwargs):
        return UpdateCheckResult(
            current_version="3.0.1",
            latest_version="3.1.0",
            update_available=True,
            installer="pip",
            upgrade_command=["python", "-m", "pip", "install", "--upgrade", "worai"],
        )

    run_called = {"value": False}

    def _stub_run(_command):
        run_called["value"] = True
        return 0

    monkeypatch.setattr("worai.commands.self_update.check_for_update", _stub_check)
    monkeypatch.setattr("worai.commands.self_update.run_upgrade_command", _stub_run)

    runner = CliRunner()
    result = runner.invoke(root_cli.app, ["self", "update"])

    assert result.exit_code == 0
    assert "Update available: 3.0.1 -> 3.1.0" in result.output
    assert "Re-run with --yes" in result.output
    assert run_called["value"] is False


def test_self_update_runs_upgrade_with_yes(monkeypatch) -> None:
    command = ["/usr/bin/python3", "-m", "pip", "install", "--upgrade", "worai"]

    def _stub_check(*_args, **_kwargs):
        return UpdateCheckResult(
            current_version="3.0.1",
            latest_version="3.1.0",
            update_available=True,
            installer="pip",
            upgrade_command=command,
        )

    seen = {"command": None}

    def _stub_run(received_command):
        seen["command"] = received_command
        return 0

    monkeypatch.setattr("worai.commands.self_update.check_for_update", _stub_check)
    monkeypatch.setattr("worai.commands.self_update.run_upgrade_command", _stub_run)

    runner = CliRunner()
    result = runner.invoke(root_cli.app, ["self", "update", "--yes"])

    assert result.exit_code == 0
    assert seen["command"] == command
    assert "Running:" in result.output


def test_self_update_reports_up_to_date(monkeypatch) -> None:
    def _stub_check(*_args, **_kwargs):
        return UpdateCheckResult(
            current_version="3.0.1",
            latest_version="3.0.1",
            update_available=False,
            installer="pip",
            upgrade_command=["python", "-m", "pip", "install", "--upgrade", "worai"],
        )

    monkeypatch.setattr("worai.commands.self_update.check_for_update", _stub_check)

    runner = CliRunner()
    result = runner.invoke(root_cli.app, ["self", "update", "--check-only"])

    assert result.exit_code == 0
    assert "worai is up to date (3.0.1)." in result.output
