"""
Screen Controller - Screenshot capture and input control.

Wraps pyautogui with safety features and consistent interface.
"""

import io
import os
import base64
import hashlib
import time
from pathlib import Path
from typing import Optional, Tuple
from datetime import datetime


class ScreenController:
    """
    Screen capture and input control via pyautogui.

    Safety features:
    - Configurable action delay
    - Failsafe corner (move mouse to corner to abort)
    - Screenshot before every action
    """

    def __init__(
        self,
        action_delay: float = 0.5,
        screenshot_dir: Optional[str] = None,
        failsafe: bool = True,
    ):
        import pyautogui
        self.pyautogui = pyautogui

        # Safety settings
        pyautogui.FAILSAFE = failsafe
        pyautogui.PAUSE = action_delay

        self.screenshot_dir = Path(screenshot_dir) if screenshot_dir else None
        if self.screenshot_dir:
            self.screenshot_dir.mkdir(parents=True, exist_ok=True)

    @property
    def screen_size(self) -> Tuple[int, int]:
        """Get screen resolution."""
        return self.pyautogui.size()

    def screenshot(self, save: bool = True) -> Tuple[bytes, str, Optional[str]]:
        """
        Capture screenshot.

        Returns:
            (png_bytes, sha256_hash, saved_path or None)
        """
        img = self.pyautogui.screenshot()

        # Convert to PNG bytes
        buf = io.BytesIO()
        img.save(buf, format="PNG")
        png_bytes = buf.getvalue()

        # Compute hash
        img_hash = hashlib.sha256(png_bytes).hexdigest()[:16]

        # Optionally save
        saved_path = None
        if save and self.screenshot_dir:
            timestamp = datetime.utcnow().strftime("%Y%m%d_%H%M%S_%f")
            saved_path = str(self.screenshot_dir / f"screenshot_{timestamp}.png")
            img.save(saved_path)

        return png_bytes, img_hash, saved_path

    def screenshot_base64(self) -> Tuple[str, str]:
        """Capture screenshot as base64 for vision API."""
        png_bytes, img_hash, _ = self.screenshot(save=False)
        b64 = base64.b64encode(png_bytes).decode("utf-8")
        return b64, img_hash

    def click(self, x: int, y: int) -> None:
        """Click at position."""
        self.pyautogui.click(x, y)

    def double_click(self, x: int, y: int) -> None:
        """Double-click at position."""
        self.pyautogui.doubleClick(x, y)

    def right_click(self, x: int, y: int) -> None:
        """Right-click at position."""
        self.pyautogui.rightClick(x, y)

    def move(self, x: int, y: int, duration: float = 0.25) -> None:
        """Move mouse to position."""
        self.pyautogui.moveTo(x, y, duration=duration)

    def drag(self, x: int, y: int, duration: float = 0.5) -> None:
        """Drag from current position to target."""
        self.pyautogui.drag(x, y, duration=duration)

    def type_text(self, text: str, interval: float = 0.02) -> None:
        """Type text with optional interval between keys."""
        self.pyautogui.typewrite(text, interval=interval)

    def press(self, key: str) -> None:
        """Press a single key."""
        self.pyautogui.press(key)

    def hotkey(self, *keys: str) -> None:
        """Press key combination (e.g., hotkey('ctrl', 'c'))."""
        self.pyautogui.hotkey(*keys)

    def scroll(self, amount: int) -> None:
        """Scroll by amount (positive=up, negative=down)."""
        self.pyautogui.scroll(amount)

    def wait(self, seconds: float) -> None:
        """Wait for specified duration."""
        time.sleep(seconds)

    def get_mouse_position(self) -> Tuple[int, int]:
        """Get current mouse position."""
        return self.pyautogui.position()
