#!/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 ``wl_cli`` 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 wl_cli.commands.git.git_flow import run_git_flow_check_text

        banner_lines = run_git_flow_check_text().splitlines()
    except ImportError:
        # wl_cli 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:]

    # Resolve a Python that has `pre_commit` installed.
    #
    # `pre_commit` is a runtime dependency of the wl tool (wl-cli), living
    # in the uv tool environment — NOT in generated projects' `.venv` (workspace
    # `dependencies = []`). Running `python -m pre_commit` against the project
    # venv fails with "No module named pre_commit". Resolve the wl tool env first.
    python_exe = None
    use_uv_tool = False

    # 1. Fast path: the python inside the wl tool env (UV_TOOL_DIR or default)
    tool_dir = os.environ.get("UV_TOOL_DIR") or os.path.join(
        os.path.expanduser("~"), ".local", "share", "uv", "tools"
    )
    for candidate in (
        os.path.join(tool_dir, "wlcli", "bin", "python"),
        os.path.join(tool_dir, "wlcli", "bin", "python3"),
        os.path.join(tool_dir, "wlcli", "Scripts", "python.exe"),
        os.path.join(tool_dir, "wlcli", "Scripts", "python3.exe"),
    ):
        if os.path.exists(candidate):
            python_exe = candidate
            break

    # 2. Fallback: run inside the tool env via uv (robust to layout changes)
    if not python_exe:
        try:
            probe = subprocess.run(
                [
                    "uv",
                    "tool",
                    "run",
                    "wlcli",
                    "python",
                    "-c",
                    "import pre_commit",
                ],
                capture_output=True,
                text=True,
                check=False,
                timeout=30,
            )
            if probe.returncode == 0:
                use_uv_tool = True
        except (subprocess.SubprocessError, FileNotFoundError):
            use_uv_tool = False

    # 3. Last resort: project `.venv` (only has pre_commit in repos that install
    #    it explicitly, e.g. wl_cli' own dev checkout)
    if not python_exe and not use_uv_tool:
        for path in (
            os.path.join(".venv", "bin", "python"),
            os.path.join(".venv", "bin", "python3"),
            os.path.join(".venv", "Scripts", "python.exe"),
        ):
            abs_path = os.path.join(os.getcwd(), path)
            if os.path.exists(abs_path):
                python_exe = abs_path
                break

    if not python_exe and not use_uv_tool:
        print(
            "`pre-commit` not found in the wl tool environment. "
            "Install it with: uv tool install wl-cli",
            file=sys.stderr,
        )
        return 1

    # Execute pre_commit
    if use_uv_tool:
        result = subprocess.run(
            ["uv", "tool", "run", "wlcli", "python", "-m", "pre_commit"] + args,
            check=False,
        )
    else:
        result = subprocess.run([python_exe, "-m", "pre_commit"] + args, check=False)

    return result.returncode


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