#!/usr/bin/env python3
"""GLEE Commons — Reproducible Test Suite for Idempotent Wake Guard

Verifies that duplicate wake signals, cron ticks, and webhook retries are
deterministically deduplicated while genuine state mutations execute immediately.

Run with: python3 test_wake_guard.py
"""

import importlib.util
import os
import shutil
import sys
import tempfile
import unittest
from pathlib import Path

# Load the downloadable sibling for both direct execution and pytest's
# importlib mode, which does not add this artifact directory to sys.path.
_spec = importlib.util.spec_from_file_location(
    "_glee_commons_wake_guard", Path(__file__).with_name("wake_guard.py")
)
_wake_guard = importlib.util.module_from_spec(_spec)
sys.modules[_spec.name] = _wake_guard
_spec.loader.exec_module(_wake_guard)
WakeGuard, WakeDecision = _wake_guard.WakeGuard, _wake_guard.WakeDecision


class TestWakeGuard(unittest.TestCase):

    def setUp(self):
        self.test_dir = Path(tempfile.mkdtemp(prefix="glee_wake_guard_test_"))
        self.store_path = self.test_dir / ".state_hash"
        self.guard = WakeGuard(state_store_path=self.store_path)

    def tearDown(self):
        shutil.rmtree(self.test_dir, ignore_errors=True)

    def test_01_cold_start_executes(self):
        """First invocation must always execute."""
        decision = self.guard.evaluate(state_dict={"task": "index_items", "queue_len": 4})
        self.assertEqual(decision.action, "EXECUTE")
        self.assertEqual(decision.reason, "cold_start")
        self.assertTrue(self.store_path.exists())

    def test_02_identical_wake_is_suppressed(self):
        """Second identical invocation must suppress without burning compute."""
        state = {"task": "index_items", "queue_len": 4}
        d1 = self.guard.evaluate(state_dict=state)
        self.assertEqual(d1.action, "EXECUTE")

        # Duplicate wake arrives (e.g. repeated cron or webhook retry)
        d2 = self.guard.evaluate(state_dict=state)
        self.assertEqual(d2.action, "SUPPRESS")
        self.assertEqual(d2.reason, "state_identical")
        self.assertIn("Wake suppressed", d2.heartbeat_message or "")

    def test_03_burst_of_10_identical_wakes(self):
        """In a burst of 10 identical events, exactly 1 executes and 9 suppress."""
        state = {"active_job": "job_123", "status": "waiting"}
        decisions = [self.guard.evaluate(state_dict=state) for _ in range(10)]

        executed = [d for d in decisions if d.action == "EXECUTE"]
        suppressed = [d for d in decisions if d.action == "SUPPRESS"]

        self.assertEqual(len(executed), 1)
        self.assertEqual(len(suppressed), 9)

    def test_04_state_mutation_executes(self):
        """When state actually changes, the wake must execute immediately."""
        state1 = {"task": "step_1", "items_processed": 0}
        d1 = self.guard.evaluate(state_dict=state1)
        self.assertEqual(d1.action, "EXECUTE")

        # State mutates
        state2 = {"task": "step_2", "items_processed": 10}
        d2 = self.guard.evaluate(state_dict=state2)
        self.assertEqual(d2.action, "EXECUTE")
        self.assertEqual(d2.reason, "state_mutated")

    def test_05_volatile_timestamp_noise_ignored(self):
        """Changes only in timestamp/time fields must NOT trigger a false execution."""
        state1 = {"task": "sync", "created_timestamp": "2026-09-17T00:00:01Z"}
        d1 = self.guard.evaluate(state_dict=state1)
        self.assertEqual(d1.action, "EXECUTE")

        # Timestamp ticks, but operational state is identical
        state2 = {"task": "sync", "created_timestamp": "2026-09-17T00:00:05Z"}
        d2 = self.guard.evaluate(state_dict=state2)
        self.assertEqual(d2.action, "SUPPRESS")

    def test_06_watched_file_changes_trigger_execution(self):
        """Watching a filesystem file correctly reacts to file modifications."""
        monitored_file = self.test_dir / "active_tasks.txt"
        monitored_file.write_text("task_1\ntask_2\n")

        d1 = self.guard.evaluate(state_files=[monitored_file])
        self.assertEqual(d1.action, "EXECUTE")

        # Unchanged file suppresses
        d2 = self.guard.evaluate(state_files=[monitored_file])
        self.assertEqual(d2.action, "SUPPRESS")

        # Mutate file
        monitored_file.write_text("task_1\ntask_2\ntask_3\n")
        d3 = self.guard.evaluate(state_files=[monitored_file])
        self.assertEqual(d3.action, "EXECUTE")
        self.assertEqual(d3.reason, "state_mutated")


if __name__ == "__main__":
    unittest.main(verbosity=2)
