import os
import time
import json
import threading

MARKER_FILE = "/tmp/bot_reload_marker"
_last_marker_time = 0
_marker_lock = threading.Lock()

def set_reload_marker():
    """Crea un marcador para indicar que se necesita recarga"""
    global _last_marker_time
    
    with _marker_lock:
        current_time = time.time()
        
        # Evitar crear marcadores muy seguidos (mínimo 2 segundos)
        if current_time - _last_marker_time < 2:
            print(f"[Marker] Marcador omitido (demasiado pronto)")
            return False
        
        try:
            with open(MARKER_FILE, 'w') as f:
                json.dump({
                    'timestamp': current_time,
                    'reason': 'channel_toggle'
                }, f)
            _last_marker_time = current_time
            print(f"[Marker] Marcador de recarga creado")
            return True
        except Exception as e:
            print(f"[Marker] Error creando marcador: {e}")
            return False

def check_reload_marker():
    """Verifica si existe un marcador de recarga"""
    try:
        if os.path.exists(MARKER_FILE):
            with open(MARKER_FILE, 'r') as f:
                data = json.load(f)
            # Eliminar el marcador
            os.remove(MARKER_FILE)
            print(f"[Marker] Marcador encontrado y eliminado: {data}")
            return True
        return False
    except Exception as e:
        print(f"[Marker] Error verificando marcador: {e}")
        return False

def clear_all_markers():
    """Limpia todos los marcadores existentes"""
    try:
        if os.path.exists(MARKER_FILE):
            os.remove(MARKER_FILE)
            print(f"[Marker] Todos los marcadores limpiados")
    except Exception as e:
        print(f"[Marker] Error limpiando marcadores: {e}")

if __name__ == "__main__":
    set_reload_marker()
