from rich.console import Console

from awspipe.repl import run_shell


class FakeSession:
    def __init__(self, lines):
        self._lines = iter(lines)

    def prompt(self):
        return next(self._lines)


class RecordingEngine:
    def __init__(self) -> None:
        self.calls = []

    def query(self, sql, profile=None, region=None, refresh=False, all_regions=False):
        self.calls.append(
            {
                "sql": sql,
                "profile": profile,
                "region": region,
                "refresh": refresh,
                "all_regions": all_regions,
            }
        )
        return object()


def test_shell_exit_aliases_return_without_query(monkeypatch) -> None:
    console = Console(record=True)
    engine = RecordingEngine()

    for line in ("quit", "exit", ".quit", ".exit"):
        monkeypatch.setattr("awspipe.repl.PromptSession", lambda _prompt, value=line: FakeSession([value]))
        run_shell(console, engine, profile="dev", region="eu-west-1", all_regions=False)

    assert engine.calls == []


def test_shell_unknown_meta_command_raises(monkeypatch) -> None:
    console = Console(record=True)
    engine = RecordingEngine()
    monkeypatch.setattr("awspipe.repl.PromptSession", lambda _prompt: FakeSession([".wat"]))

    try:
        run_shell(console, engine, profile=None, region=None, all_regions=False)
    except ValueError as exc:
        assert str(exc) == "Unknown shell command: .wat"
    else:
        raise AssertionError("expected unknown meta command to raise")
