"""
Clipboard operations using Windows API via C# helper
"""

import subprocess
import os
from typing import Optional, List
from pathlib import Path

# Path to the compiled helper
_HELPER_EXE = Path(__file__).parent / "helpers" / "WindowsHelper.exe"


def _ensure_helper_built():
    """Ensure the helper executable exists"""
    if not _HELPER_EXE.exists():
        raise FileNotFoundError(
            f"WindowsHelper.exe not found at {_HELPER_EXE}. "
            "Please run build_windows_helper.ps1 to compile it."
        )


def get_text() -> Optional[str]:
    """
    Get text from the clipboard.

    Returns:
        The clipboard text as a string, or None if clipboard is empty or doesn't contain text

    Example:
        >>> text = get_text()
        >>> if text:
        ...     print(f"Clipboard: {text}")
    """
    _ensure_helper_built()

    try:
        result = subprocess.run(
            [str(_HELPER_EXE), "clipboard", "get"],
            capture_output=True,
            text=True,
            timeout=5,
            creationflags=subprocess.CREATE_NO_WINDOW if os.name == 'nt' else 0
        )

        if result.returncode == 0:
            return result.stdout.strip()
        return None

    except Exception as e:
        print(f"Error getting clipboard text: {e}")
        return None


def set_text(text: str) -> bool:
    """
    Set text to the clipboard.

    Args:
        text: The text to copy to clipboard

    Returns:
        True if successful, False otherwise

    Example:
        >>> set_text("Hello, World!")
        >>> print("Text copied to clipboard")
    """
    _ensure_helper_built()

    try:
        result = subprocess.run(
            [str(_HELPER_EXE), "clipboard", "set", text],
            capture_output=True,
            text=True,
            timeout=5,
            creationflags=subprocess.CREATE_NO_WINDOW if os.name == 'nt' else 0
        )

        return result.returncode == 0

    except Exception as e:
        print(f"Error setting clipboard text: {e}")
        return False


def clear() -> bool:
    """
    Clear the clipboard.

    Returns:
        True if successful, False otherwise

    Example:
        >>> clear()
        >>> print("Clipboard cleared")
    """
    _ensure_helper_built()

    try:
        result = subprocess.run(
            [str(_HELPER_EXE), "clipboard", "clear"],
            capture_output=True,
            text=True,
            timeout=5,
            creationflags=subprocess.CREATE_NO_WINDOW if os.name == 'nt' else 0
        )

        return result.returncode == 0

    except Exception as e:
        print(f"Error clearing clipboard: {e}")
        return False


def get_files() -> Optional[List[str]]:
    """
    Get file paths from the clipboard.

    Returns:
        List of file paths, or None if clipboard doesn't contain files

    Example:
        >>> files = get_files()
        >>> if files:
        ...     for file in files:
        ...         print(f"File: {file}")
    """
    _ensure_helper_built()

    try:
        result = subprocess.run(
            [str(_HELPER_EXE), "clipboard", "getfiles"],
            capture_output=True,
            text=True,
            timeout=5,
            creationflags=subprocess.CREATE_NO_WINDOW if os.name == 'nt' else 0
        )

        if result.returncode == 0:
            files = result.stdout.strip().split('\n')
            return [f.strip() for f in files if f.strip()]
        return None

    except Exception as e:
        print(f"Error getting clipboard files: {e}")
        return None


def set_files(files: List[str]) -> bool:
    """
    Set file paths to the clipboard.

    Args:
        files: List of file/folder paths to copy to clipboard

    Returns:
        True if successful, False otherwise

    Example:
        >>> set_files(["C:\\Users\\file1.txt", "C:\\Users\\file2.txt"])
        >>> print("Files copied to clipboard")
    """
    _ensure_helper_built()

    try:
        cmd = [str(_HELPER_EXE), "clipboard", "setfiles"] + files
        result = subprocess.run(
            cmd,
            capture_output=True,
            text=True,
            timeout=5,
            creationflags=subprocess.CREATE_NO_WINDOW if os.name == 'nt' else 0
        )

        return result.returncode == 0

    except Exception as e:
        print(f"Error setting clipboard files: {e}")
        return False


def copy(text: str) -> bool:
    """
    Alias for set_text() - copy text to clipboard.

    Args:
        text: The text to copy

    Returns:
        True if successful, False otherwise

    Example:
        >>> copy("Hello!")
    """
    return set_text(text)


def paste() -> Optional[str]:
    """
    Alias for get_text() - get text from clipboard.

    Returns:
        The clipboard text, or None if empty

    Example:
        >>> text = paste()
        >>> if text:
        ...     print(text)
    """
    return get_text()
