#!/usr/bin/env python3
# File generated by pre-commit: https://pre-commit.com
# ID: 138fd403232d2ddd5efb44317e38bf03
# Modified to be a Python script for cross-platform compatibility
# Added Git Flow hint display

import os
import shutil
import subprocess
import sys


def run_git_flow_check():
    """Run git-flow check and display hint information.

    This is a pure hint: the return code is discarded by the caller and the
    check never gates the commit. Resolution order:
      1. In-process call to the git-flow check core when ``py_wlcommands`` is
         importable under the current interpreter (no subprocess spawned).
      2. Fall back to ``wl git-flow check`` when ``wl`` is on PATH.
      3. If neither is available, silently skip and return 0.
    """
    banner_lines = []

    # 1. Prefer the in-process core so we do not spawn uv/wl.
    try:
        from py_wlcommands.commands.git.git_flow import run_git_flow_check_text

        banner_lines = run_git_flow_check_text().splitlines()
    except ImportError:
        # py_wlcommands is not importable under pre-commit's python -> CLI fallback.
        banner_lines = _run_wl_cli_check()
    except Exception:
        # The in-process core failed for another reason (e.g. not a git repo,
        # missing PyYAML). Still a pure hint: fall back to the wl CLI, and if
        # that is also unavailable, skip silently.
        banner_lines = _run_wl_cli_check()

    if banner_lines:
        _print_git_flow_banner(banner_lines)

    return 0


def _run_wl_cli_check():
    """Fall back to ``wl git-flow check`` on PATH; return banner lines or []."""
    wl_exe = shutil.which("wl")
    if wl_exe is None:
        return []
    try:
        result = subprocess.run(
            [wl_exe, "git-flow", "check"],
            capture_output=True,
            text=True,
            check=False,
        )
    except (FileNotFoundError, OSError):
        return []

    stdout = result.stdout.strip()
    return stdout.split("\n") if stdout else []


def _print_git_flow_banner(lines):
    """Print the key git-flow status lines under the bilingual banner."""
    print("\n=== Git Flow Status ===")
    print("=== Git Flow 状态 ===")
    for line in lines:
        # Only show key information (not the full agent hint)
        if line.startswith(
            (
                "Git Flow check:",
                "Branch:",
                "Type:",
                "Source:",
                "Target:",
                "Rule:",
                "Fix:",
            )
        ):
            print(line)
    print("=" * 50)


def main():
    """Main function to execute pre-commit hook."""
    print("✓ Pre-commit hook is running...")
    print("✓ Pre-commit钩子正在运行...")

    # Run Git Flow check and display hint
    run_git_flow_check()

    # Get the directory where this script is located
    here = os.path.dirname(os.path.abspath(__file__))

    # Generate arguments
    args = [
        "hook-impl",
        "--config=.wl/.pre-commit-config.yaml",
        "--hook-type=pre-commit",
        "--hook-dir",
        here,
        "--",
    ] + sys.argv[1:]

    # Try to find Python executable
    python_paths = [
        # Try uv Python first
        "uv",
        "python",
        "--print-path",
        # Try virtual environment paths
        os.path.join(".venv", "bin", "python"),
        os.path.join(".venv", "bin", "python3"),
        os.path.join("..", ".venv", "bin", "python"),
        os.path.join("..", ".venv", "bin", "python3"),
        os.path.join("../../", ".venv", "bin", "python"),
        os.path.join("../../", ".venv", "bin", "python3"),
        # Windows virtual environment paths
        os.path.join(".venv", "Scripts", "python.exe"),
        os.path.join(".venv", "Scripts", "python3.exe"),
        os.path.join("..", ".venv", "Scripts", "python.exe"),
        os.path.join("..", ".venv", "Scripts", "python3.exe"),
        # System Python
        "python",
        "python3",
    ]

    python_exe = None

    # Try uv first
    try:
        uv_result = subprocess.run(
            ["uv", "python", "--print-path"], capture_output=True, text=True, check=True
        )
        python_exe = uv_result.stdout.strip()
    except (subprocess.CalledProcessError, FileNotFoundError):
        # Try other paths
        for path in python_paths[1:]:
            if os.path.isabs(path):
                abs_path = path
            else:
                abs_path = os.path.join(os.getcwd(), path)

            if os.path.exists(abs_path):
                python_exe = abs_path
                break

    if not python_exe:
        print(
            "`pre-commit` not found.  Did you forget to activate your virtualenv?",
            file=sys.stderr,
        )
        return 1

    # Execute pre_commit
    if python_exe == "python" or python_exe == "python3":
        # Direct Python call
        result = subprocess.run([python_exe, "-m", "pre_commit"] + args, check=False)
    else:
        # Use the specific Python path
        result = subprocess.run([python_exe, "-m", "pre_commit"] + args, check=False)

    return result.returncode


if __name__ == "__main__":
    sys.exit(main())
