import pyautogui
import numpy as np
from .core import Camera
from .hands import HandTracker

class Aelion:
    """
    The Master Controller for the Aelion Vision Ecosystem.
    Simplifies complex AI tasks into single-line commands.
    """
    def __init__(self, debug=True):
        self.debug = debug
        self.cam = None
        self.hands = None
        
    def init_mouse(self, width=1280, height=720):
        """Initializes the hardware for Spatial Mouse control."""
        self.cam = Camera(mirror=True, width=width, height=height)
        self.hands = HandTracker(max_hands=1, detection_confidence=0.7, tracking_confidence=0.5)
        pyautogui.PAUSE = 0
        pyautogui.FAILSAFE = False
        return self.cam

    def spatial_mouse(self, frame, sensitivity=6, draw_zone=150):
        """
        The One-Line Mouse Controller.
        Logic: Peace Sign = Move, Index Only = Click/Draw.
        """
        w_scr, h_scr = pyautogui.size()
        w_cam, h_cam = frame.shape[1], frame.shape[0]
        
        # Track hand
        frame = self.hands.find_hands(frame, draw=self.debug)
        lm = self.hands.lm_list
        
        if len(lm) != 0:
            x1, y1 = lm[8][1], lm[8][2]
            fingers = self.hands.fingers_up()
            
            # Map coordinates
            mx = np.interp(x1, (draw_zone, w_cam - draw_zone), (0, w_scr))
            my = np.interp(y1, (draw_zone, h_cam - draw_zone), (0, h_scr))
            
            # Move & Click Logic
            if fingers[1] == 1:
                pyautogui.moveTo(mx, my) # Simplified movement for the user
                
                if fingers[2] == 0: # Only Index is up -> CLICK
                    pyautogui.mouseDown()
                else: # Both up -> RELEASE
                    pyautogui.mouseUp()
                    
        return frame