"""End-to-end tests for the mes-courriels CLI."""

import signal
import subprocess


def test_cli_with_known_sender():
    """CLI returns messages from a known sender."""
    result = subprocess.run(
        ["uv", "run", "mes-courriels", "noreply@google.com", "-n", "1"],
        capture_output=True,
        text=True,
        timeout=30,
    )
    assert result.returncode == 0
    assert len(result.stdout.strip()) > 0


def test_cli_with_unknown_sender():
    """CLI prints 'No messages' for a sender with no results."""
    result = subprocess.run(
        ["uv", "run", "mes-courriels", "nobody-ever-12345@nonexistent.example"],
        capture_output=True,
        text=True,
        timeout=30,
    )
    assert result.returncode == 0
    assert "No messages" in result.stdout


def test_cli_help():
    """CLI --help works and shows usage."""
    result = subprocess.run(
        ["uv", "run", "mes-courriels", "--help"],
        capture_output=True,
        text=True,
        timeout=10,
    )
    assert result.returncode == 0
    assert "sender" in result.stdout


def test_cli_watch_mode_starts():
    """Watch mode starts, seeds existing IDs, and prints watching message."""
    proc = subprocess.Popen(
        ["uv", "run", "mes-courriels", "noreply@google.com", "-w", "-i", "300"],
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        text=True,
    )
    try:
        # Wait for the "Watching" message (means seed phase completed)
        line = proc.stdout.readline()
        assert "Watching" in line
        assert "noreply@google.com" in line
    finally:
        proc.send_signal(signal.SIGTERM)
        proc.wait(timeout=5)
