"""FingerLock – Surveillance avec déverrouillage par schéma"""
import time, threading
from typing import Dict, Any
from pynput import mouse, keyboard
from fingerlock.utils.logger import setup_logger, log_lock, log_system
from fingerlock.core.locker import lock_system
from fingerlock.core.pattern import verify_pattern

class ActivityMonitor:
    def __init__(self):
        self.last_activity = time.time()
        self.running = True

    def on_move(self, x, y):
        self.last_activity = time.time()

    def on_click(self, x, y, button, pressed):
        self.last_activity = time.time()

    def on_key(self, key):
        self.last_activity = time.time()


def run_watch(config: Dict[str, Any]) -> None:
    setup_logger(config["log_path"])

    lock_delay = config.get("lock_delay_seconds", 10)
    pattern_hash = config.get("pattern_hash")

    print(f"\n  ⌨️  Surveillance active")
    print(f"  ⏱️  Verrouillage après {lock_delay}s d'inactivité")
    print(f"  🔐 Déverrouillage par schéma pavé numérique")
    print(f"  Ctrl+C pour arrêter\n")

    log_system("Surveillance démarrée")

    monitor = ActivityMonitor()

    mouse_listener = mouse.Listener(
        on_move=monitor.on_move,
        on_click=monitor.on_click
    )
    keyboard_listener = keyboard.Listener(
        on_press=monitor.on_key
    )

    mouse_listener.start()
    keyboard_listener.start()

    try:
        locked = False

        while monitor.running:
            now = time.time()
            inactivity = now - monitor.last_activity

            if inactivity >= lock_delay and not locked:
                # Verrouiller
                print(f"\n  [🔒 LOCK] {int(inactivity)}s d'inactivité → Verrouillage")
                log_lock(f"Verrouillage après {int(inactivity)}s")
                lock_system(config.get("platform_lock", "auto"))
                locked = True

                # Stopper les listeners pendant la vérification
                mouse_listener.stop()
                keyboard_listener.stop()

                # Demander le schéma
                if pattern_hash:
                    unlocked = verify_pattern(pattern_hash)
                else:
                    unlocked = True  # Pas de schéma configuré

                if unlocked:
                    log_system("Système déverrouillé")
                    locked = False
                    monitor.last_activity = time.time()

                    # Redémarrer les listeners
                    monitor.running = True
                    mouse_listener = mouse.Listener(
                        on_move=monitor.on_move,
                        on_click=monitor.on_click
                    )
                    keyboard_listener = keyboard.Listener(
                        on_press=monitor.on_key
                    )
                    mouse_listener.start()
                    keyboard_listener.start()
                else:
                    print("  ⚠️  Trop de tentatives. Surveillance arrêtée.")
                    log_system("Surveillance arrêtée - trop de tentatives")
                    break

            elif inactivity < lock_delay:
                remaining = int(lock_delay - inactivity)
                print(f"  [✅ ACTIF] Dernière activité : {int(inactivity)}s (lock dans {remaining}s)     ", end="\r")

            time.sleep(0.5)

    except KeyboardInterrupt:
        print("\n\n  🛑  Surveillance arrêtée\n")
        log_system("Arrêt manuel")
        monitor.running = False
    finally:
        try:
            mouse_listener.stop()
            keyboard_listener.stop()
        except:
            pass
