import argparse
import shutil
import subprocess
import sys
import time
from datetime import datetime

# PowerShell command that calls Win32 mouse_event to jiggle the mouse 1px right then 1px left.
# MOUSEEVENTF_MOVE = 0x0001
PS_JIGGLE = (
    "Add-Type -TypeDefinition '"
    "using System; using System.Runtime.InteropServices; "
    "public class Win32 { "
    '[DllImport("user32.dll")] '
    "public static extern void mouse_event(int dwFlags, int dx, int dy, int dwData, IntPtr dwExtraInfo); "
    "}';"
    "[Win32]::mouse_event(1, 1, 0, 0, [IntPtr]::Zero);"
    "[Win32]::mouse_event(1, -1, 0, 0, [IntPtr]::Zero)"
)


def check_environment():
    """Verify that powershell.exe is accessible via WSL interop."""
    if not shutil.which("powershell.exe"):
        print(
            "Error: powershell.exe not found on PATH.\n"
            "This tool requires WSL with Windows interop enabled.\n"
            "Make sure you're running inside WSL and that interop is not disabled\n"
            "(check /etc/wsl.conf for [interop] enabled=true).",
            file=sys.stderr,
        )
        sys.exit(1)


def jiggle(verbose: bool) -> bool:
    """Send a mouse jiggle via PowerShell. Returns True on success."""
    result = subprocess.run(
        ["powershell.exe", "-NoProfile", "-NonInteractive", "-Command", PS_JIGGLE],
        capture_output=True,
        timeout=10,
    )
    if result.returncode != 0:
        print(
            f"[{datetime.now():%H:%M:%S}] PowerShell error: {result.stderr.decode().strip()}",
            file=sys.stderr,
        )
        return False
    if verbose:
        print(f"[{datetime.now():%H:%M:%S}] Mouse jiggled")
    return True


def main():
    parser = argparse.ArgumentParser(
        prog="keepmeawake",
        description="Keep Microsoft Teams online by periodically jiggling the mouse via WSL PowerShell interop.",
    )
    parser.add_argument(
        "-i", "--interval",
        type=int,
        default=60,
        help="Seconds between each mouse jiggle (default: 60)",
    )
    parser.add_argument(
        "-v", "--verbose",
        action="store_true",
        help="Log each jiggle with timestamp",
    )
    args = parser.parse_args()

    if args.interval < 1:
        print("Error: interval must be at least 1 second.", file=sys.stderr)
        sys.exit(1)

    check_environment()

    print(f"keepmeawake running — jiggling every {args.interval}s")
    print("Press Ctrl+C to stop.")

    try:
        while True:
            jiggle(args.verbose)
            time.sleep(args.interval)
    except KeyboardInterrupt:
        print("\nStopped.")


if __name__ == "__main__":
    main()
