
#!/usr/bin/env python3
import sys
import subprocess
import os
import signal

# Handle SIGPIPE
try:
    from signal import SIGPIPE, SIG_DFL

    signal.signal(SIGPIPE, SIG_DFL)
except ImportError:
    # Not available on Windows
    pass


def usage():
    print(
        """Usage: pzf <subcommand> [fzf-options...]

Subcommands:
  git-branch          Select a local git branch
  git-remote-branch   Select a remote git branch
  git-staged-file     Select a staged file from git diff --cached
  git-modified-file   Select a modified file from git diff HEAD
  git-unstaged-file   Select an unstaged file from git diff
  git-untracked-file  Select an untracked file

Examples:
  pzf git-branch
  pzf git-branch --multi
  pzf git-staged-file --preview 'git diff --cached {1}'""",
        file=sys.stderr,
    )


def has_preview(args):
    return any(arg == "--preview" or arg.startswith("--preview=") for arg in args)


def run_fzf(producer_cmd, fzf_args, default_preview=None, filter_func=None):
    """
    Runs the pipeline: producer_cmd | [filter] | fzf
    """
    # 1. Prepare fzf command
    cmd_fzf = ["fzf"] + fzf_args
    if default_preview and not has_preview(fzf_args):
        # Determine strict preview command if possible, but passing as string is standard for fzf
        cmd_fzf.extend(["--preview", default_preview])

    # 2. Environment (Optional fix for Windows/MinGW if needed)
    # These were relevant for the original shell script in MinGW/MSYS, but not for Python subprocess.
    env = os.environ.copy()

    try:
        # Case 1: Filtering needed (Python middleman)
        if filter_func:
            # We must use text=True to process lines
            p_prod = subprocess.Popen(
                producer_cmd,
                stdout=subprocess.PIPE,
                text=True,
                encoding="utf-8",
                errors="replace",
            )
            p_fzf = subprocess.Popen(
                cmd_fzf,
                stdin=subprocess.PIPE,
                text=True,
                encoding="utf-8",
                errors="replace",
                env=env,
            )

            try:
                for line in p_prod.stdout:
                    if filter_func(line):
                        p_fzf.stdin.write(line)
                p_fzf.stdin.close()
            except BrokenPipeError:
                pass  # fzf closed early
            except IOError:
                pass

            p_prod.wait()
            p_fzf.wait()
            sys.exit(p_fzf.returncode)

        # Case 2: Direct piping
        else:
            p_prod = subprocess.Popen(producer_cmd, stdout=subprocess.PIPE)
            p_fzf = subprocess.Popen(cmd_fzf, stdin=p_prod.stdout, env=env)

            # Allow p_prod to receive SIGPIPE if fzf closes
            p_prod.stdout.close()

            p_fzf.wait()
            p_prod.wait()
            sys.exit(p_fzf.returncode)

    except KeyboardInterrupt:
        sys.exit(130)
    except FileNotFoundError as e:
        print(f"Error: Command not found: {e.filename}", file=sys.stderr)
        sys.exit(127)


# --- Subcommand Implementations ---


def git_branch(args):
    preview = "git -c color.ui=always log --oneline --graph -10 {1}"
    cmd = ["git", "branch", "--format=%(refname:short)"]
    run_fzf(cmd, args, default_preview=preview)


def git_remote_branch(args):
    preview = "git -c color.ui=always log --oneline --graph -10 {1}"
    cmd = ["git", "for-each-ref", "--format=%(refname:short)", "refs/remotes/"]

    # Defaults for remote branch (prepend so user can override?)
    # FZF takes last value. So we prepend defaults.
    # Note: We use '/' as delimiter. Native fzf on Windows accepts it fine via subprocess.
    defaults = ["--delimiter=/", "--accept-nth=2.."]

    def flt(line):
        return "HEAD" not in line and "/" in line

    run_fzf(cmd, defaults + args, default_preview=preview, filter_func=flt)


def git_staged_file(args):
    preview = "git -c color.ui=always diff --cached {1}"
    cmd = ["git", "diff", "--name-only", "--cached"]
    run_fzf(cmd, args, default_preview=preview)


def git_modified_file(args):
    preview = "git -c color.ui=always diff HEAD {1}"
    cmd = ["git", "diff", "--name-only", "HEAD"]
    run_fzf(cmd, args, default_preview=preview)


def git_unstaged_file(args):
    preview = "git -c color.ui=always diff {1}"
    cmd = ["git", "diff", "--name-only"]
    run_fzf(cmd, args, default_preview=preview)


def git_untracked_file(args):
    preview = 'bat -n 50 {1} 2>/dev/null || echo "Binary or empty file"'
    cmd = ["git", "ls-files", "--others", "--exclude-standard"]
    run_fzf(cmd, args, default_preview=preview)


def list_subcommands():
    cmds = [
        "git-branch",
        "git-remote-branch",
        "git-staged-file",
        "git-modified-file",
        "git-unstaged-file",
        "git-untracked-file",
    ]
    for c in cmds:
        print(c)


def main():
    if len(sys.argv) < 2:
        usage()
        sys.exit(1)

    subcommand = sys.argv[1]
    fzf_args = sys.argv[2:]

    if subcommand in ["-h", "--help"]:
        usage()
        sys.exit(0)
    if subcommand in ["-l", "--list"]:
        list_subcommands()
        sys.exit(0)

    dispatch = {
        "git-branch": git_branch,
        "git-remote-branch": git_remote_branch,
        "git-staged-file": git_staged_file,
        "git-modified-file": git_modified_file,
        "git-unstaged-file": git_unstaged_file,
        "git-untracked-file": git_untracked_file,
    }

    if subcommand in dispatch:
        dispatch[subcommand](fzf_args)
    else:
        print(f"Unknown subcommand: {subcommand}", file=sys.stderr)
        usage()
        sys.exit(1)


if __name__ == "__main__":
    main()
