import os
import json
import pytest
from pathlib import Path

from pulse.core import interoception
from pulse.core import event_bus

@pytest.fixture
def clean_interoception():
    if interoception.SIGNALS_FILE.exists():
        interoception.SIGNALS_FILE.unlink()
    interoception._signals.clear()
    event_bus._subscribers.clear()
    yield
    if interoception.SIGNALS_FILE.exists():
        interoception.SIGNALS_FILE.unlink()

def test_sample_updates_state(clean_interoception):
    interoception.sample()
    assert interoception._signals["memory_pressure"]["current_value"] >= 0
    assert len(interoception._signals["memory_pressure"]["trend"]) == 1

    interoception.sample({"error_rate": 0.5})
    assert interoception._signals["error_rate"]["current_value"] == 0.5
    assert len(interoception._signals["error_rate"]["trend"]) == 1

def test_get_alerts(clean_interoception):
    alerts_published = []
    def on_alert(event):
        alerts_published.append(event)
        
    event_bus.subscribe("interoception.alert", on_alert)
    
    interoception.load_signals()
    
    # Trigger standard alert
    interoception.update_signal("error_rate", 0.99) # over 0.15 threshold
    
    # Trigger inverse alert
    interoception.update_signal("extraction_yield", 0.1) # under 0.3 threshold
    
    alerts = interoception.get_alerts()
    
    assert len(alerts) == 2
    assert len(alerts_published) == 2
    
    alert_signals = [a["signal"] for a in alerts]
    assert "error_rate" in alert_signals
    assert "extraction_yield" in alert_signals

def test_trend_limit(clean_interoception):
    interoception.load_signals()
    for i in range(15):
        interoception.update_signal("agent_load", float(i))
        
    trend = interoception._signals["agent_load"]["trend"]
    assert len(trend) == 10
    assert trend[-1] == 14.0
    assert trend[0] == 5.0
