"""Tests for session-picker."""

from datetime import UTC, datetime
from unittest.mock import MagicMock, patch

import pytest
from session_picker.picker import _format_choice, _format_last_activity
from session_picker.resume import resume_session

from session_store.models import SessionInfo


def test_format_last_activity_just_now() -> None:
    """Format a recent timestamp as 'just now'."""
    now = datetime.now(UTC)
    assert _format_last_activity(now) == "just now"


def test_format_last_activity_minutes_ago() -> None:
    """Format a timestamp from minutes ago."""
    now = datetime.now(UTC)
    past = now.replace(minute=now.minute - 5)
    result = _format_last_activity(past)
    assert result == "5m ago"


def test_format_last_activity_hours_ago() -> None:
    """Format a timestamp from hours ago."""
    now = datetime.now(UTC)
    past = now.replace(hour=now.hour - 2)
    result = _format_last_activity(past)
    assert result == "2h ago"


def test_format_last_activity_days_ago() -> None:
    """Format a timestamp from days ago."""
    now = datetime.now(UTC)
    past = now.replace(day=now.day - 3)
    result = _format_last_activity(past)
    assert result == "3d ago"


def test_format_choice() -> None:
    """Format a SessionInfo as a questionary choice title."""
    session = SessionInfo(
        tool="devin",
        session_id="forest-aries",
        title="Test session",
        message_count=5,
        last_activity=datetime(2026, 8, 6, 18, 41, 0, tzinfo=UTC),
        working_directory="C:\\Users\\Surface",
    )
    choice = _format_choice(session)
    assert "forest-aries" in choice
    assert "Test session" in choice
    assert "C:\\Users\\Surface" in choice


def test_resume_session_dry_run(capsys: pytest.CaptureFixture[str]) -> None:
    """dry_run prints the session ID and returns 0."""
    exit_code = resume_session("forest-aries", dry_run=True)
    assert exit_code == 0
    captured = capsys.readouterr()
    assert captured.out.strip() == "forest-aries"


@patch("session_picker.resume.shutil.which")
def test_resume_session_devin_not_found(mock_which: MagicMock) -> None:
    """Returns 1 when devin is not on PATH."""
    mock_which.return_value = None
    exit_code = resume_session("forest-aries")
    assert exit_code == 1
