"""
Screenshot capture and analysis for AiCippy CLI.

Cross-platform screenshot capture with automatic analysis via the AI agent.
Supports macOS (screencapture), Linux (scrot/gnome-screenshot), Windows (PowerShell).
"""

from __future__ import annotations

import platform
import subprocess
from datetime import datetime
from pathlib import Path
from typing import Final

from aicippy.utils.logging import get_logger

logger = get_logger(__name__)

# Screenshot output directory (relative to working directory)
SCREENSHOTS_FOLDER: Final[str] = "screenshots"


def capture_screenshot(
    output_dir: Path | None = None,
    region: bool = False,
    window: bool = False,
) -> Path | None:
    """
    Capture a screenshot using OS-native tools.

    Args:
        output_dir: Directory to save screenshot. Defaults to cwd/screenshots/.
        region: If True, capture a selected region (macOS/Linux only).
        window: If True, capture the focused window (macOS only).

    Returns:
        Path to the saved screenshot file, or None if capture failed.
    """
    if output_dir is None:
        output_dir = Path.cwd() / SCREENSHOTS_FOLDER

    output_dir.mkdir(parents=True, exist_ok=True)

    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    filename = f"screenshot_{timestamp}.png"
    output_path = output_dir / filename

    system = platform.system().lower()

    try:
        if system == "darwin":
            # macOS: screencapture
            cmd = ["screencapture"]
            if region:
                cmd.append("-s")  # Interactive selection
            elif window:
                cmd.append("-w")  # Window capture
            cmd.append(str(output_path))
            result = subprocess.run(cmd, capture_output=True, timeout=30)
            if result.returncode != 0:
                logger.warning(
                    "screenshot_failed_macos",
                    returncode=result.returncode,
                    stderr=result.stderr.decode(),
                )
                return None

        elif system == "linux":
            # Linux: try scrot, then gnome-screenshot, then import (ImageMagick)
            captured = False
            for tool_cmd in [
                ["scrot", "-s" if region else "", str(output_path)],
                [
                    "gnome-screenshot",
                    "-a" if region else "-f",
                    str(output_path),
                ],
                ["import", str(output_path)] if region else ["import", "-window", "root", str(output_path)],
            ]:
                # Filter empty strings
                tool_cmd = [c for c in tool_cmd if c]
                try:
                    result = subprocess.run(
                        tool_cmd, capture_output=True, timeout=30,
                    )
                    if result.returncode == 0:
                        captured = True
                        break
                except FileNotFoundError:
                    continue
            if not captured:
                logger.warning("screenshot_failed_linux_no_tool")
                return None

        elif system == "windows":
            # Windows: PowerShell screenshot via .NET
            ps_script = f"""
Add-Type -AssemblyName System.Windows.Forms
$screen = [System.Windows.Forms.Screen]::PrimaryScreen.Bounds
$bitmap = New-Object System.Drawing.Bitmap($screen.Width, $screen.Height)
$graphics = [System.Drawing.Graphics]::FromImage($bitmap)
$graphics.CopyFromScreen($screen.Location, [System.Drawing.Point]::Empty, $screen.Size)
$bitmap.Save('{output_path}')
$graphics.Dispose()
$bitmap.Dispose()
"""
            result = subprocess.run(
                ["powershell", "-Command", ps_script],
                capture_output=True,
                timeout=30,
            )
            if result.returncode != 0:
                logger.warning(
                    "screenshot_failed_windows",
                    returncode=result.returncode,
                )
                return None
        else:
            logger.warning("screenshot_unsupported_platform", system=system)
            return None

        # Verify file was created
        if output_path.exists() and output_path.stat().st_size > 0:
            logger.info(
                "screenshot_captured",
                path=str(output_path),
                size=output_path.stat().st_size,
            )
            return output_path

        logger.warning("screenshot_file_empty_or_missing", path=str(output_path))
        return None

    except subprocess.TimeoutExpired:
        logger.warning("screenshot_timeout")
        return None
    except Exception as e:
        logger.warning("screenshot_error", error=str(e))
        return None


def get_screenshot_tools() -> list[str]:
    """Return list of available screenshot tools on this system."""
    system = platform.system().lower()
    tools: list[str] = []

    if system == "darwin":
        tools.append("screencapture (macOS built-in)")
    elif system == "linux":
        for tool in ["scrot", "gnome-screenshot", "import"]:
            try:
                subprocess.run(
                    [tool, "--version"],
                    capture_output=True,
                    timeout=5,
                )
                tools.append(tool)
            except (FileNotFoundError, subprocess.TimeoutExpired):
                continue
    elif system == "windows":
        tools.append("PowerShell (.NET System.Windows.Forms)")

    return tools
