# tests/test_heartbeat_idle.py
from datetime import datetime, timedelta
from pathlib import Path

import pytest

from nanobot.heartbeat.service import HeartbeatService
from nanobot.session.manager import SessionManager


@pytest.mark.asyncio
async def test_heartbeat_skips_when_user_active():
    """Test that heartbeat doesn't trigger if user messaged recently."""
    workspace = Path("/tmp/test-heartbeat")
    workspace.mkdir(exist_ok=True)

    # Create session with recent user message
    sessions = SessionManager(workspace)
    session = sessions.get_or_create("telegram:239824268")
    session.add_message("user", "Recent message")
    sessions.save(session)

    # Create heartbeat callback
    callback_called = False
    async def on_heartbeat(prompt, metadata=None):
        nonlocal callback_called
        callback_called = True
        return "response"

    # Create heartbeat service
    service = HeartbeatService(
        workspace=workspace,
        on_heartbeat=on_heartbeat,
        interval_s=1,  # Short interval for testing
        enabled=True,
        session_manager=sessions,
        target_session_key="telegram:239824268"
    )

    # Trigger heartbeat
    await service._tick()

    # Callback should NOT have been called (user was active recently)
    assert not callback_called


@pytest.mark.asyncio
async def test_heartbeat_triggers_when_user_idle():
    """Test that heartbeat triggers after 30min of inactivity."""
    workspace = Path("/tmp/test-heartbeat")
    workspace.mkdir(exist_ok=True)

    # Create HEARTBEAT.md with content
    heartbeat_file = workspace / "HEARTBEAT.md"
    heartbeat_file.write_text("# Tasks\n- Check something\n")

    # Create session with old user message (>30min ago)
    sessions = SessionManager(workspace)
    session = sessions.get_or_create("telegram:239824268")

    # Manually set old timestamp
    old_timestamp = (datetime.now() - timedelta(minutes=31)).isoformat()
    session.messages.append({
        "role": "user",
        "content": "Old message",
        "timestamp": old_timestamp
    })
    sessions.save(session)

    # Create heartbeat callback
    callback_called = False
    callback_metadata = None

    async def on_heartbeat(prompt, metadata=None):
        nonlocal callback_called, callback_metadata
        callback_called = True
        callback_metadata = metadata
        return "response"

    # Create heartbeat service
    service = HeartbeatService(
        workspace=workspace,
        on_heartbeat=on_heartbeat,
        interval_s=1,
        enabled=True,
        session_manager=sessions,
        target_session_key="telegram:239824268"
    )

    # Trigger heartbeat
    await service._tick()

    # Callback SHOULD have been called (user idle for >30min)
    assert callback_called
    assert callback_metadata == {"suppress_output": True}
