#!/usr/bin/env python3
"""
Cross-platform pnpm command wrapper.
Finds pnpm correctly on Windows (handles pnpm.cmd) and Unix systems.
"""

import shutil
import subprocess
import sys


def find_pnpm():
    """
    Find pnpm executable on the system.
    Returns the path to pnpm or None if not found.
    """
    # Try to find pnpm using shutil.which
    # On Windows, this will find pnpm.cmd if it's in PATH
    pnpm_path = shutil.which("pnpm")

    if pnpm_path:
        return pnpm_path

    # On Windows, also try pnpm.cmd explicitly
    if sys.platform == "win32":
        pnpm_cmd = shutil.which("pnpm.cmd")
        if pnpm_cmd:
            return pnpm_cmd

    return None


def main():
    """Main entry point - execute pnpm with provided arguments."""
    pnpm_path = find_pnpm()

    if not pnpm_path:
        print("Error: pnpm not found in PATH.", file=sys.stderr)
        print("\nPlease install pnpm:", file=sys.stderr)
        print("  Windows: https://pnpm.io/installation#on-windows", file=sys.stderr)
        print("  Unix: https://pnpm.io/installation#on-posix-systems", file=sys.stderr)
        sys.exit(1)

    # Get all arguments passed to this script
    args = sys.argv[1:]

    # Execute pnpm with the provided arguments
    try:
        sys.exit(subprocess.call([pnpm_path] + args))
    except KeyboardInterrupt:
        # Handle Ctrl+C gracefully
        sys.exit(130)
    except Exception as e:
        print(f"Error executing pnpm: {e}", file=sys.stderr)
        sys.exit(1)


if __name__ == "__main__":
    main()
