import threading
import time

class GlobalWorkPool:
    """Thread-safe pool of unassigned tasks that can be claimed by any node."""
    def __init__(self):
        self.lock = threading.Lock()
        self.available = {} # task_id -> {"payload": p, "ts": time.time()}
        self.on_new_work = None # Callback to notify nodes
        threading.Thread(target=self._cleanup_loop, daemon=True, name="WorkPoolCleanup").start()
    
    def _cleanup_loop(self):
        import time
        while True:
            time.sleep(300)
            now = time.time()
            with self.lock:
                to_remove = [tid for tid, d in self.available.items() if (now - d["ts"]) > 3600]
                for tid in to_remove:
                    del self.available[tid]

    def push_work(self, task_id, payload):
        """Adds new task to global discovery pool."""
        import time
        with self.lock:
            self.available[task_id] = {"payload": payload, "ts": time.time()}
            print(f"    [📦] New Shared Task: {task_id}")
        if self.on_new_work:
            self.on_new_work(task_id)

    def claim(self, task_id, node_id):
        """Allows a node to pull a specific task from the pool."""
        with self.lock:
            if task_id in self.available:
                print(f"    [📦] Task {task_id} Claimed by {node_id}")
                return True, self.available.pop(task_id)["payload"]
            return False, None
    
    def list_available(self):
        """Returns IDs of all currently available unclaimed tasks."""
        with self.lock:
            return list(self.available.keys())
