"""Tests for the top-level `abreka chat` command."""

from __future__ import annotations

from unittest.mock import patch

from click.testing import CliRunner

from abreka.cli import main


class TestProjectChatCLI:
    def test_launches_pi_with_project_chat_session_dir(self, abreka_project, monkeypatch):
        monkeypatch.chdir(abreka_project)
        runner = CliRunner()
        execvp_calls = []

        def fake_execvp(file, args):
            execvp_calls.append((file, args))
            raise SystemExit(0)

        with (
            patch("shutil.which", return_value="/usr/bin/pi"),
            patch("os.execvp", side_effect=fake_execvp),
            patch("os.chdir"),
        ):
            result = runner.invoke(main, ["chat"])

        assert result.exit_code == 0, result.output
        assert len(execvp_calls) == 1
        file, args = execvp_calls[0]
        assert file == "pi"
        assert "--append-system-prompt" in args
        assert "--session-dir" in args
        assert str(abreka_project / "abreka" / "chats") in args
        assert "project" in args[-1].lower()
        assert "Launching pi for project test-project" in result.output

    def test_fails_if_pi_not_found(self, abreka_project, monkeypatch):
        monkeypatch.chdir(abreka_project)
        runner = CliRunner()

        with patch("shutil.which", return_value=None):
            result = runner.invoke(main, ["chat"])

        assert result.exit_code != 0
        assert "pi not found" in result.output.lower()
