import os
import json
import time
import uuid
import tempfile

class GridNode:
    """
    Represents a node in a Peer-to-Peer Grid Computing Swarm.
    Mocks peer discovery using local file-based tracking for testing.
    """
    def __init__(self, node_id=None, registry_dir=None):
        self.node_id = node_id or str(uuid.uuid4())
        # Use a temporary directory as a shared mock registry if none is provided
        self.registry_dir = registry_dir or os.path.join(tempfile.gettempdir(), 'brynq_grid_registry')
        os.makedirs(self.registry_dir, exist_ok=True)
        self.presence_file = os.path.join(self.registry_dir, f"{self.node_id}.json")

    def advertise_presence(self):
        """
        Advertises this node's presence to the mock registry.
        """
        data = {
            "node_id": self.node_id,
            "last_seen": time.time(),
            "status": "active"
        }
        with open(self.presence_file, 'w') as f:
            json.dump(data, f)

    def discover_peers(self, timeout=60):
        """
        Discovers peers in the mock registry that have been seen within the timeout period.
        """
        peers = []
        if not os.path.exists(self.registry_dir):
            return peers
            
        current_time = time.time()
        for filename in os.listdir(self.registry_dir):
            if filename.endswith('.json') and filename != f"{self.node_id}.json":
                filepath = os.path.join(self.registry_dir, filename)
                try:
                    with open(filepath, 'r') as f:
                        data = json.load(f)
                        if current_time - data.get('last_seen', 0) <= timeout:
                            peers.append(data)
                except (json.JSONDecodeError, IOError):
                    pass
        return peers
        
    def cleanup(self):
        """
        Removes this node's presence from the registry.
        """
        if os.path.exists(self.presence_file):
            try:
                os.remove(self.presence_file)
            except OSError:
                pass
