import pytest
from datetime import datetime, timezone, timedelta
from pulse.brain import reconsolidation
from pulse.core import event_bus

@pytest.fixture
def clean_labile():
    if reconsolidation.LABILE_ITEMS_FILE.exists():
        reconsolidation.LABILE_ITEMS_FILE.unlink()
    reconsolidation._labile_state.clear()
    event_bus._subscribers.clear()
    yield
    if reconsolidation.LABILE_ITEMS_FILE.exists():
        reconsolidation.LABILE_ITEMS_FILE.unlink()

def test_mark_labile(clean_labile):
    reconsolidation.mark_labile("test_id", "lessons")
    assert "test_id" in reconsolidation._labile_state
    assert reconsolidation._labile_state["test_id"]["table"] == "lessons"

def test_sweep_expired(clean_labile):
    # Manually add expired item
    past = (datetime.now(timezone.utc) - timedelta(seconds=60)).isoformat()
    reconsolidation._labile_state["expired_id"] = {"table": "lessons", "expires_at": past}
    
    # Manually add valid item
    future = (datetime.now(timezone.utc) + timedelta(seconds=60)).isoformat()
    reconsolidation._labile_state["valid_id"] = {"table": "lessons", "expires_at": future}
    
    reconsolidation.save_labile()
    
    reconsolidation.sweep_expired()
    assert "expired_id" not in reconsolidation._labile_state
    assert "valid_id" in reconsolidation._labile_state

def test_reinforce_fails_if_not_labile(clean_labile):
    assert not reconsolidation.reinforce("missing_id")