from datetime import UTC, datetime, timedelta
from tests.conftest import app_config
from worker_watcher.models import AgentRegistration, RemoteEvent
from worker_watcher.watcher import Watcher
def test_remote_worker_registers_and_duplicate_event_is_idempotent(tmp_path) -> None:
watcher = Watcher(app_config(tmp_path / "remote.sqlite"), tmp_path)
agent = AgentRegistration("agent.remote.carlo", "Carlo", "0.1", "vps", "carlo", "python", ("heartbeat", "run_events"))
event = RemoteEvent("event-1", agent, "worker.carlo.transcript", "youtube.transcript.batch", "heartbeat",
datetime(2026, 8, 1, 12, 0, tzinfo=UTC), {"display_name": "Transcript", "stale_after_seconds": 60})
try:
first = watcher.ingest_remote_event(event)
second = watcher.ingest_remote_event(event)
assert first["accepted"] and not first["duplicate"]
assert second["duplicate"]
assert watcher.connection.execute("SELECT COUNT(*) FROM execution_agents").fetchone()[0] == 1
assert watcher.connection.execute("SELECT COUNT(*) FROM remote_events").fetchone()[0] == 1
row = watcher.repository.status_rows()[0]
assert row["worker_key"] == "worker.carlo.transcript"
assert row["location_type"] == "vps"
assert row["host"] == "carlo"
watcher.repository.refresh_remote_staleness(datetime.now(UTC) + timedelta(seconds=180), 120)
stale_row = watcher.repository.status_rows()[0]
assert stale_row["observation_status"] == "stale"
assert stale_row["health_status"] == "stale"
finally:
watcher.close()