#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# BSD 3-Clause License
#
# Copyright (c) 2025, Bjoern Hendrik Fock
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
#    this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
#    this list of conditions and the following disclaimer in the documentation
#    and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors
#    may be used to endorse or promote products derived from this software
#    without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# pylint: disable=invalid-name
# pylint: disable=too-many-lines
#
"""
git-cl: A pre-staging layer for organising changes in Git.

GitHub: https://github.com/BHFock/git-cl
DOI:    https://doi.org/10.5281/zenodo.18722077

git-cl brings changelist support to Git, allowing developers to partition
modified files into named groups before staging or committing. Changelists
persist across sessions in a JSON file inside the .git directory, and
integrate transparently with existing Git workflows.

Features:
- Group files into named changelists (add, remove, status)
- Prune stale entries left behind by plain 'git commit'
- Stage, unstage, commit, or diff by changelist
- Checkout (revert) changelist files to HEAD
- Stash and unstash changelists selectively
- Promote a changelist to a dedicated branch (late-binding branching)

Single file, zero dependencies beyond Python 3.9+ and Git.
Cross-platform: Unix (fcntl) and Windows (msvcrt) file locking.
"""

__version__ = "1.8.0"

import argparse
import datetime
import json
import os
import re
import shlex
import subprocess
import sys
import tempfile
if sys.platform == "win32":
    import msvcrt
else:
    import fcntl
from contextlib import contextmanager
from pathlib import Path
from typing import Callable, Iterable, Iterator, Optional

if sys.version_info < (3, 9):
    print("Error: git-cl requires Python 3.9+", file=sys.stderr)
    sys.exit(1)

# Try to import colorama for coloured output of 'git cl st'
# use dummy objects if colorama is not available to avoid NameError
try:
    from colorama import Fore, Style
    COLORAMA_AVAILABLE = True
except ImportError:
    COLORAMA_AVAILABLE = False

    # pylint: disable=too-few-public-methods
    class _DummyColorama:
        BLUE = ""
        GREEN = ""
        MAGENTA = ""
        RED = ""
        RESET_ALL = ""
    Fore = _DummyColorama()
    Style = _DummyColorama()

def _relpath(path, start):
    """
    Like os.path.relpath, but always returns forward slashes.

    Only the separator of the platform is replaced: on Linux and macOS a
    backslash is an ordinary character in a file name.
    """
    rel = os.path.relpath(path, start)
    if os.sep != "/":
        rel = rel.replace(os.sep, "/")
    return rel

# =============================================================================
# INTERNAL UTILITIES
# =============================================================================

# Set by 'git cl commit' for its own 'git commit' call. A post-commit hook
# running 'git cl prune' then returns immediately, so that the hook only
# acts on commits made outside git-cl. Otherwise it would empty a
# changelist committed with --keep, and its changes would be overwritten
# when 'git cl commit' saves the changelists it loaded before committing.
NO_PRUNE_ENV = "GIT_CL_NO_PRUNE"


class ClutilSaveError(OSError):
    """
    Raised when changelist or stash metadata cannot be written.

    The save functions print the reason before raising, so callers only
    need to stop and report failure. main() turns an unhandled one into
    exit code 1, which keeps commands from reporting success when their
    changes were not saved.
    """


class ClutilLoadError(Exception):
    """
    Raised when 'cl.json' or 'cl-stashes.json' cannot be read or is invalid.

    The load functions print the reason and how to recover before raising.
    main() turns it into exit code 1, so that no command carries on with
    empty data and overwrites the file on its next save.
    """


# Note: Some utility functions call CLI command functions like cl_stash and
#       cl_unstash. These are defined later in the module but are called by
#       utility functions.


def clutil_print_error(*values: object, **kwargs) -> None:
    """
    Prints an error, a warning or a hint that belongs to one on stderr.

    Keeping these messages off stdout lets scripts and integrations tell
    regular output apart from problems, as Git itself does. Takes the
    same arguments as print().
    """
    print(*values, file=sys.stderr, **kwargs)


# Control characters (C0, DEL and C1). A terminal acts on some of them: ESC
# starts sequences that move the cursor, clear the screen or set the window
# title. File names may contain them, so they are never printed as they are.
_CONTROL_CHARS = re.compile("[\x00-\x1f\x7f-\x9f]")
_CONTROL_ESCAPES = {"\a": "\\a", "\b": "\\b", "\t": "\\t", "\n": "\\n",
                    "\v": "\\v", "\f": "\\f", "\r": "\\r"}


def clutil_escape_control_chars(text: str, keep: str = "") -> str:
    """
    Replaces control characters with the escapes Git uses for file names.

    'Notes\\x1b[2J.md' becomes 'Notes\\033[2J.md': common characters get a
    short escape ('\\t', '\\n', ...), others the octal value of each of their
    UTF-8 bytes, as in 'git status'. Other characters, including non-ASCII
    letters, are kept.

    Args:
        text: The text to escape.
        keep: Control characters to leave as they are, such as the newlines
              of a multi-line message.

    Returns:
        str: The text without control characters other than those in keep.
    """
    def escape(match: "re.Match[str]") -> str:
        char = match.group()
        if char in keep:
            return char
        return _CONTROL_ESCAPES.get(char) or "".join(
            f"\\{byte:03o}" for byte in char.encode("utf-8"))

    return _CONTROL_CHARS.sub(escape, text)


class ClutilEscapingStream:
    """
    Wraps sys.stdout or sys.stderr and escapes control characters.

    Messages include file names from Git and from the metadata files, and
    changelist names from the metadata files. main() installs this wrapper
    for both streams, so that none of them can send control sequences to
    the terminal. Newlines are kept. The coloured lines of 'git cl status'
    go through write_unescaped(), see clutil_print_status_line().
    """

    def __init__(self, stream):
        self._stream = stream

    def write(self, text: str) -> int:
        self._stream.write(clutil_escape_control_chars(text, keep="\n"))
        return len(text)

    def write_unescaped(self, text: str) -> int:
        return self._stream.write(text)

    def __getattr__(self, name: str):
        return getattr(self._stream, name)


def clutil_print_status_line(line: str) -> None:
    """
    Prints a line from clutil_format_file_status() on stdout.

    The line may hold colour codes, which would be escaped like any other
    control character on the way through ClutilEscapingStream. Its path has
    already been escaped by clutil_format_file_status(), so it is written
    without escaping.
    """
    write = getattr(sys.stdout, "write_unescaped", sys.stdout.write)
    write(line + "\n")


@contextmanager
def clutil_file_lock(lock_path: Path):
    """
    Acquires an exclusive lock on a file for safe concurrent access.

    Creates a lock file and acquires an exclusive lock to prevent concurrent
    access to shared resources. The lock file is automatically cleaned up
    when the context exits, regardless of whether an exception occurs.

    Args:
        lock_path (Path): Path to the lock file to create and lock.

    Yields:
        None

    Raises:
        OSError: If the lock file cannot be created or locked.

    Platform notes:
        On Unix, ``fcntl.flock`` acquires a whole-file advisory lock that
        blocks indefinitely until the lock becomes available.
        On Windows, ``msvcrt.locking`` locks a single byte (the file is
        empty and used only for mutual exclusion, so one byte suffices).
        Unlike ``fcntl.flock``, ``msvcrt.locking`` with ``LK_LOCK`` retries
        for approximately ten seconds before raising ``OSError``.  This is
        acceptable because changelist operations are fast.

    Example:
        >>> lock_file = Path('.git/cl.lock')
        >>> with clutil_file_lock(lock_file):
        ...     # Perform operations that need exclusive access
        ...     pass
        # Lock file is automatically cleaned up here
    """
    lock_file = None
    try:
        lock_file = open(lock_path, 'w', encoding='utf-8')
        if sys.platform == "win32":
            msvcrt.locking(lock_file.fileno(), msvcrt.LK_LOCK, 1)
        else:
            fcntl.flock(lock_file, fcntl.LOCK_EX)
        yield
    finally:
        if lock_file:
            if sys.platform == "win32":
                try:
                    msvcrt.locking(lock_file.fileno(), msvcrt.LK_UNLCK, 1)
                except OSError:
                    pass
            else:
                fcntl.flock(lock_file, fcntl.LOCK_UN)
            lock_file.close()
            lock_path.unlink(missing_ok=True)


def clutil_should_use_color(args) -> bool:
    """
    Determines whether coloured output should be used in CLI display.

    This function checks multiple conditions to decide if colour formatting
    is appropriate:
    - The --no-color flag is not set.
    - The NO_COLOR environment variable is not set.
    - The output is being sent to a terminal (TTY).
    - The 'colorama' module is available.

    Args:
        args (argparse.Namespace): Parsed command-line arguments, expected to
                                   include the 'no_color' attribute.

    Returns:
        bool: True if coloured output should be enabled, False otherwise.
    """
    # Like Git, no colour for terminals that cannot show it (e.g. Emacs shell)
    no_color_env = (bool(os.environ.get('NO_COLOR'))
                    or os.environ.get('TERM') == 'dumb')
    is_tty = sys.stdout.isatty()
    return (not (args.no_color or no_color_env or not is_tty) and
            COLORAMA_AVAILABLE)


def clutil_report_failure(action: str, error: Exception) -> None:
    """
    Report a failed operation without Python's exception text.

    A failed Git command has usually explained the problem already; output
    that git-cl captured is shown here instead. Other errors (e.g. OSError)
    are shown as they are.
    """
    if not isinstance(error, subprocess.CalledProcessError):
        clutil_print_error(f"Error: {action}: {error}")
        return
    captured = error.stderr if isinstance(error.stderr, str) else ""
    for line in captured.strip().splitlines():
        clutil_print_error(line)
    command = " ".join(error.cmd[:2]) if isinstance(error.cmd, list) else "git"
    clutil_print_error(f"Error: {action}: '{command}' failed "
                       f"(exit code {error.returncode}).")


def clutil_resolve_commit_message(args: argparse.Namespace) -> Optional[str]:
    """
    Resolves the commit message from CLI arguments.

    Args:
        args (argparse.Namespace): Parsed arguments with 'message' or 'file'.

    Returns:
        Optional[str]: The commit message, or None if resolution fails.
    """
    if args.message:
        return args.message

    if args.file:
        try:
            return clutil_read_commit_message_file(args.file)
        except (OSError, ValueError) as error:
            clutil_print_error(f"Error reading commit message file '{args.file}': "
                               f"{error}")
            return None

    clutil_print_error("Error: No commit message provided.")
    return None


def clutil_get_file() -> Path:
    """
    Returns the path to the changelist file inside the Git directory.

    Returns:
        Path: Path to the '.git/cl.json' file.

    Raises:
        SystemExit: If not inside a Git repository.
    """
    try:
        git_dir = subprocess.check_output(
            ["git", "rev-parse", "--git-dir"],
            stderr=subprocess.DEVNULL,
            text=True
        ).strip()
        return Path(git_dir) / "cl.json"
    except subprocess.CalledProcessError:
        clutil_print_error("Error: Not inside a Git repository.")
        clutil_print_error("Please run this command from within a Git repository.")
        sys.exit(1)


def clutil_is_string_list(value) -> bool:
    """Return True if value is a list of strings."""
    return isinstance(value, list) and all(isinstance(v, str) for v in value)


def clutil_check_changelist_data(data) -> Optional[str]:
    """
    Check that loaded changelist data has the expected structure.

    Args:
        data: Parsed content of 'cl.json'

    Returns:
        A description of the first problem found, or None if the data is
        a mapping of changelist names to lists of file paths.
    """
    if not isinstance(data, dict):
        return "expected an object mapping changelist names to file lists"
    for name, files in data.items():
        if not clutil_is_string_list(files):
            return f"changelist '{name}' is not a list of file paths"
    return None


def clutil_check_stash_data(data) -> Optional[str]:
    """
    Check that loaded stash metadata has the fields git-cl relies on.

    Args:
        data: Parsed content of 'cl-stashes.json'

    Returns:
        A description of the first problem found, or None if every entry
        has a 'stash_ref' string and a 'files' list, and 'file_categories',
        if present, maps category names to lists of file paths.
    """
    if not isinstance(data, dict):
        return "expected an object mapping changelist names to stash records"
    for name, record in data.items():
        if not isinstance(record, dict):
            return f"the record for '{name}' is not an object"
        if not isinstance(record.get("stash_ref"), str):
            return f"the record for '{name}' has no valid 'stash_ref'"
        if not clutil_is_string_list(record.get("files")):
            return f"the record for '{name}' has no valid 'files' list"
        if not isinstance(record.get("stash_commit", ""), str):
            return f"the record for '{name}' has an invalid 'stash_commit'"
        categories = record.get("file_categories", {})
        if not (isinstance(categories, dict) and
                all(clutil_is_string_list(v) for v in categories.values())):
            return f"the record for '{name}' has invalid 'file_categories'"
    return None


def clutil_read_json_file(
    path: Path,
    check: Callable[[object], Optional[str]]
) -> dict:
    """
    Read and check a git-cl metadata file.

    An empty file counts as no data. Any other problem stops git-cl:
    carrying on with empty data would overwrite the file on the next save
    and lose everything in it.

    Args:
        path: File to read
        check: Function returning a problem description or None

    Returns:
        dict: The parsed data.

    Raises:
        ClutilLoadError: If the file cannot be read, is not valid JSON or
            fails the check. The reason has already been printed.
    """
    try:
        with open(path, "r", encoding="utf-8") as file_handle:
            content = file_handle.read()
        if not content.strip():
            return {}
        data = json.loads(content)
        problem = check(data)
    except OSError as error:
        problem = error.strerror or str(error)
    except (json.JSONDecodeError, UnicodeDecodeError) as error:
        problem = f"not valid JSON ({error})"
    if problem is None:
        return data

    clutil_print_error(f"Error: Cannot use {path}: {problem}.")
    clutil_print_error("git-cl has stopped, so that the file is not "
                       "overwritten.")
    clutil_print_load_recovery_hint(path)
    raise ClutilLoadError(str(path))


def clutil_print_load_recovery_hint(path: Path) -> None:
    """
    Print how to recover from an unusable metadata file.

    Args:
        path: The unusable 'cl.json' or 'cl-stashes.json'
    """
    clutil_print_error("Repair the file, or move it aside to continue "
                       "without it:")
    clutil_print_error(f"  mv {shlex.quote(str(path))} "
                       f"{shlex.quote(str(path) + '.broken')}")
    if path.name == "cl-stashes.json":
        clutil_print_error("git-cl then no longer knows its stashed "
                           "changelists. Their changes stay in "
                           "'git stash list'.")
    else:
        clutil_print_error("git-cl then starts without changelists. Your "
                           "files are not affected.")


def clutil_load() -> dict[str, list[str]]:
    """
    Loads changelist data from the 'cl.json' file.

    Returns:
        dict: A mapping of changelist names to lists of file paths.

    Raises:
        ClutilLoadError: If the file exists but cannot be used. The reason
            has already been printed.
    """
    changelist_file = clutil_get_file()
    lock_file = changelist_file.with_suffix('.lock')
    if changelist_file.exists():
        with clutil_file_lock(lock_file):
            return clutil_read_json_file(changelist_file,
                                         clutil_check_changelist_data)
    return {}


def clutil_save(data: dict[str, list[str]]) -> None:
    """
    Saves the changelist data to 'cl.json', omitting empty changelists.

    Writes are atomic: the data is first written to a temporary file in the
    same directory, then renamed over the target. If the process is
    interrupted mid-write, the original file is left untouched.

    Args:
        data (dict): Mapping of changelist names to lists of files.

    Raises:
        ClutilSaveError: If the file cannot be written. The error has
            already been printed.
    """
    changelist_file = clutil_get_file()
    lock_file = changelist_file.with_suffix('.lock')
    cleaned = {k: v for k, v in data.items() if v}
    with clutil_file_lock(lock_file):
        tmp_path = None
        try:
            fd, tmp_path = tempfile.mkstemp(
                dir=changelist_file.parent,
                prefix='.cl.json.',
                suffix='.tmp'
            )
            with os.fdopen(fd, 'w', encoding='utf-8') as file_handle:
                json.dump(cleaned, file_handle, indent=2)
            os.replace(tmp_path, changelist_file)
            tmp_path = None  # successfully renamed, nothing to clean up
        except OSError as error:
            clutil_print_error(f"Error saving changelists: {error}")
            raise ClutilSaveError(str(error)) from error
        finally:
            if tmp_path is not None:
                try:
                    os.unlink(tmp_path)
                except OSError:
                    pass


def clutil_validate_name(name: str) -> bool:
    """
    Validates that a changelist name is safe to use.

    Args:
        name (str): The changelist name to validate.

    Returns:
        bool: True if the name is valid, False otherwise.
    """
    # Check for empty names
    if not name:
        return False

    # Check for reasonable length (max 100 characters)
    if len(name) > 100:
        return False

    # Only allow safe characters: letters, numbers, hyphens, underscores, dots
    allowed_chars = set(
        'abcdefghijklmnopqrstuvwxyz'
        'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
        '0123456789-_.'
    )

    if not all(char in allowed_chars for char in name):
        return False

    # Don't allow names that are only dots (filesystem issues)
    if all(char == '.' for char in name):
        return False

    # Check for Git reserved words (only the critical ones)
    reserved_names = {'HEAD', 'FETCH_HEAD', 'ORIG_HEAD', 'MERGE_HEAD',
                      'CHERRY_PICK_HEAD', 'index'}
    if name in reserved_names:
        return False

    return True


def clutil_plural(count: int, singular: str, plural: str = "") -> str:
    """Return e.g. '1 file' or '3 files'."""
    return f"{count} {singular if count == 1 else (plural or singular + 's')}"


def clutil_has_commits() -> bool:
    """Return True if HEAD points to a commit, False before the first one."""
    result = subprocess.run(["git", "rev-parse", "--verify", "--quiet", "HEAD"],
                            capture_output=True, text=True, check=False)
    return result.returncode == 0


def clutil_is_skip_worktree(path: Path) -> bool:
    """
    Return True if a tracked file is outside the sparse checkout.

    Such a file is tracked and unchanged, but Git does not write it to
    the working directory ('git ls-files -t' marks it with 'S').
    """
    result = subprocess.run(["git", "ls-files", "-t", "--"]
                            + clutil_literal_pathspecs([str(path)]),
                            capture_output=True, text=True, check=False)
    return result.stdout.startswith("S ")


def clutil_get_git_root() -> Path:
    """
    Returns the absolute path to the root of the current Git repository.

    Returns:
        Path: The top-level directory of the Git repository.

    Raises:
        SystemExit: If the current directory is not inside a Git repository.
    """
    result = subprocess.run(["git", "rev-parse", "--show-toplevel"],
                            capture_output=True, text=True, check=False)
    if result.returncode == 0:
        return Path(result.stdout.strip()).resolve()
    bare = subprocess.run(["git", "rev-parse", "--is-bare-repository"],
                          capture_output=True, text=True, check=False)
    if bare.stdout.strip() == "true":
        clutil_print_error("Error: This is a bare repository. git-cl needs a "
                           "working directory with files.")
    else:
        clutil_print_error("Error: Not inside a Git repository.")
    sys.exit(1)


def clutil_get_git_status(
        include_untracked: bool = False
) -> list[tuple[str, str, Optional[str]]]:
    """
    Returns the entries of 'git status --porcelain -z'.

    The -z form gives every path exactly as it is, separated by NUL bytes.
    Without it, Git puts paths with spaces in double quotes and, by
    default, writes non-ASCII characters such as umlauts as octal escapes
    ("\\303\\234bersicht.md"), so they would not match the paths stored
    in changelists.

    Args:
        include_untracked (bool): If True, includes untracked files using
                                  '--untracked-files=all'.

    Returns:
        list of (code, path, orig_path): The two-letter status code, the
        path, and for a rename or copy the original path (else None).
        Paths are relative to the git root.

    Raises:
        SystemExit: If the git command fails.
    """
    cmd = ["git", "status", "--porcelain", "-z"]
    if include_untracked:
        cmd.append("--untracked-files=all")
    else:
        cmd.append("--untracked-files=no")

    try:
        output = subprocess.check_output(cmd)
    except subprocess.CalledProcessError as error:
        clutil_report_failure("Could not read the Git status", error)
        sys.exit(1)

    # Decode as Git writes paths: UTF-8, keeping undecodable bytes intact
    fields = output.decode("utf-8", errors="surrogateescape").split("\0")

    entries = []
    index = 0
    while index < len(fields):
        field = fields[index]
        index += 1
        if len(field) < 4:
            continue  # trailing empty field or malformed entry
        code, path = field[:2], field[3:]
        orig_path = None
        # A rename or copy is followed by a second field: the original path
        if "R" in code or "C" in code:
            if index < len(fields):
                orig_path = fields[index]
                index += 1
        entries.append((code, path, orig_path))
    return entries


def clutil_resolve_file(path: Path) -> Path:
    """
    Make a file path absolute without following a symlink in its last
    component.

    Git treats a symbolic link as a file of its own and never follows it.
    Path.resolve() does follow it, which would turn 'link.txt' into the
    file it points to. So only the directories before the last component
    are resolved; '..' and '.' are normalised first.

    Args:
        path: An absolute path, or one relative to the current directory

    Returns:
        The absolute path, with the last component kept as it is.
    """
    path = Path(os.path.abspath(path))
    if path.name in ("", ".", ".."):
        return path.resolve()
    return path.parent.resolve() / path.name


def clutil_path_exists(path: Path) -> bool:
    """
    Whether a path exists, counting a symlink as existing even if it
    points to a missing file.
    """
    return os.path.lexists(path)


def clutil_is_real_dir(path: Path) -> bool:
    """
    Whether a path is a directory and not a symlink to one. Git tracks a
    symlink to a directory as a single file.
    """
    return path.is_dir() and not path.is_symlink()


def clutil_sanitize_path(file_path: str, git_root: Path) -> Optional[str]:
    """
    Sanitizes and validates a file path for safe use with Git commands.

    Args:
        file_path (str): The file path to sanitize
        git_root (Path): The root directory of the Git repository

    Returns:
        str | None: The sanitized path relative to git_root, or None if invalid
    """
    try:
        # Convert to Path object and resolve any relative components
        path = Path(file_path)

        # If it's relative, make it relative to current working directory
        if not path.is_absolute():
            path = Path.cwd().resolve() / path

        # Resolve any .. or . components and get absolute path. A symlink
        # in the last component is kept: it is a file of its own for Git.
        path = clutil_resolve_file(path)

        # Ensure the path is within the Git repository
        try:
            relative_path = path.relative_to(git_root)
        except ValueError:
            # Path is outside the Git repository
            return None

        # Convert back to string using forward slashes (Git standard)
        sanitized = relative_path.as_posix()

        # Basic security check: reject paths with dangerous characters
        dangerous_chars = [';', '|', '&', '`', '$', '\n', '\r', '\0']
        if any(char in sanitized for char in dangerous_chars):
            return None

        return sanitized

    except (OSError, ValueError, RuntimeError):
        # Any path resolution errors
        return None


def clutil_literal_pathspecs(paths: Iterable[str]) -> list[str]:
    """
    Marks paths for Git as literal file names, not patterns.

    Git reads paths after '--' as pathspecs: '*', '?' and '[' are
    wildcards, and a leading ':' starts pathspec magic. A changelist entry
    such as '*.md' would otherwise also stage, stash or show x.md. The
    ':(literal)' prefix applies to each path only, so Git hooks and
    other commands run by Git are not affected.

    If GIT_LITERAL_PATHSPECS is set, Git takes all paths literally and
    would read the prefix as part of the name, so the paths are returned
    unchanged.

    Args:
        paths: File paths as passed to Git (repository- or CWD-relative).
    Returns:
        list[str]: The paths, each with the ':(literal)' prefix.
    """
    literal_env = os.environ.get("GIT_LITERAL_PATHSPECS", "").strip().lower()
    if literal_env in ("1", "true", "yes", "on"):
        return list(paths)
    return [f":(literal){path}" for path in paths]


def clutil_ignores_case() -> bool:
    """
    Returns True if Git treats paths case-insensitively in this repository
    (core.ignorecase, set by Git on macOS and Windows file systems).
    """
    result = subprocess.run(["git", "config", "--bool", "core.ignorecase"],
                            capture_output=True, text=True, check=False)
    return result.stdout.strip() == "true"


def clutil_match_case(rel_path: str, known: Iterable[str],
                      git_root: Path) -> str:
    """
    Returns the spelling of a path that Git and the file system use, for
    a path typed in another case on a case-insensitive file system.

    Git compares paths case-sensitively, so 'readme.md' typed for the
    file 'README.md' would never match its status, diff or stage. The
    spelling of a known path wins (Git's index, status or stored
    changelist entries); otherwise each component is matched against the
    directory listing. Only call this when clutil_ignores_case() is True.

    Args:
        rel_path: Path relative to the repository root, as typed.
        known: Paths relative to the root whose spelling is authoritative.
        git_root: The root directory of the Git repository.
    Returns:
        str: The matching spelling, or rel_path if there is no single match.
    """
    known = list(known)
    if rel_path in known:
        return rel_path
    folded = rel_path.casefold()
    matches = sorted({k for k in known if k.casefold() == folded})
    if len(matches) == 1:
        return matches[0]
    if matches:
        return rel_path

    current = git_root
    parts = []
    for part in rel_path.split("/"):
        try:
            names = os.listdir(current)
        except OSError:
            return rel_path
        if part not in names:
            candidates = [n for n in names if n.casefold() == part.casefold()]
            if len(candidates) != 1:
                return rel_path
            part = candidates[0]
        parts.append(part)
        current = current / part
    return "/".join(parts)


def clutil_known_paths(git_root: Path, status_map: dict[str, str],
                       changelists: dict[str, list[str]]) -> list[str]:
    """
    Returns paths relative to the repository root whose spelling Git
    knows: tracked files, changed files and stored changelist entries.
    """
    result = subprocess.run(["git", "ls-files", "-z"], cwd=git_root,
                            capture_output=True, text=True, check=False)
    known = [p for p in result.stdout.split("\0") if p]
    known.extend(status_map)
    for files in changelists.values():
        known.extend(files)
    return known


def clutil_status_path_to_rel(raw_path: str, git_root: Path) -> str:
    """
    Convert a path from 'git status --porcelain' output to a path relative
    to the git root, in POSIX form.
    """
    abs_path = clutil_resolve_file(git_root / raw_path)
    try:
        return abs_path.relative_to(git_root).as_posix()
    except ValueError:
        return raw_path


def clutil_get_renames() -> dict[str, str]:
    """
    Get the renames staged in the index.

    Returns:
        dict[str, str]: Mapping of new path to old path, both relative to
                        the git root.
    """
    git_root = clutil_get_git_root()
    renames = {}
    for code, new_path, old_path in clutil_get_git_status(
            include_untracked=False):
        if code[:1] == 'R' and old_path is not None:
            renames[clutil_status_path_to_rel(new_path, git_root)] = \
                clutil_status_path_to_rel(old_path, git_root)
    return renames


def clutil_note_split_renames(
        names: list[str], changelists: dict[str, list[str]],
        renames: dict[str, str], git_root: Path) -> list[str]:
    """
    Build a note for each rename where only one of the two paths is in
    the given changelists.

    A rename is only committed as a rename when both the old and the new
    path are committed together. With only one of them in a changelist,
    git cl commit would commit just the addition or just the deletion.

    Args:
        names: Changelist names to check, as one group
        changelists: Loaded changelist data
        renames: Mapping of new path to old path from clutil_get_renames()
        git_root: Repository root

    Returns:
        The note lines, empty if no rename is split.
    """
    files = {path for name in names for path in changelists.get(name, [])}
    cwd = Path.cwd().resolve()
    target = names[0] if len(names) == 1 else None

    def show(path: str) -> str:
        return _relpath(clutil_resolve_file(git_root / path), cwd)

    lines = []
    for new_path, old_path in sorted(renames.items()):
        if (new_path in files) == (old_path in files):
            continue
        if new_path in files:
            present, missing, verb = new_path, old_path, "renamed from"
        else:
            present, missing, verb = old_path, new_path, "renamed to"
        where = (f"changelist '{target}'" if target
                 else "the changelists being committed")
        lines.append(f"Note: '{show(present)}' was {verb} "
                     f"'{show(missing)}', which is not in {where}.")
        if target:
            lines.append(f"      Add it with 'git cl add {target} "
                         f"{show(missing)}' to commit the rename.")
    return lines


def clutil_get_file_status_map(
        include_untracked: bool = True) -> dict[str, str]:
    """
    Get a mapping of files to their Git 2-letter status codes.

    Every status code Git reports is included, as with 'git status'.
    Until 1.6.x, uncommon codes such as type changes ('T ') were left
    out by default. Files in a changelist with such a code were then
    shown with a wrong status, for example 'MD' as missing ('[XX]') or
    ' A' (intent to add) as unchanged ('[  ]').

    Ignored files are not included, since 'git status --porcelain' does
    not list them unless explicitly requested with '--ignored'.

    Args:
        include_untracked (bool): If True (default), list every untracked file.
            If False, untracked files are excluded entirely from the status map.

    Returns:
        dict[str, str]: Mapping of relative file paths
                        to their Git status codes.
    """
    git_root = clutil_get_git_root()
    output = clutil_get_git_status(include_untracked=include_untracked)

    status_map: dict[str, str] = {}

    for code, raw_path, old_path in output:
        # Handle renamed files. In the index the old path is a staged
        # deletion, so record it as 'D ' as well. Otherwise it has no
        # status and looks like a file missing from the branch.
        if code.startswith('R') and old_path is not None:
            old_rel = clutil_status_path_to_rel(old_path, git_root)
            status_map.setdefault(old_rel, 'D ')

        status_map[clutil_status_path_to_rel(raw_path, git_root)] = code

    return status_map


def clutil_format_file_status(
        file: str, status_map: dict[str, str], git_root: Path,
        use_color: bool = True) -> str:
    """
    Format a file's Git status line with optional color-coded output.
    Paths are shown relative to the current working directory, with
    control characters escaped. Print the line with
    clutil_print_status_line().
    """
    abs_file = clutil_resolve_file(git_root / file)
    rel_to_cwd = _relpath(abs_file, Path.cwd().resolve())
    shown_path = clutil_escape_control_chars(rel_to_cwd)

    rel_to_git_root = abs_file.relative_to(git_root).as_posix()
    status = status_map.get(rel_to_git_root, "  ")

    # Add detection of files which are deleted (committed) but still
    # included in a changelists
    if (not clutil_path_exists(abs_file) and status == "  "
            and not clutil_is_skip_worktree(abs_file)):
        status = "XX"  # Custom code for missing file
        clutil_print_error(f"Warning: The file '{rel_to_cwd}' does not exist "
                           "and is unknown to Git.\n"
                           "         It may have been deleted and committed, "
                           "exist only on another branch,\n"
                           "         or be in a stash. To remove it from its "
                           f"changelist: git cl rm {shlex.quote(rel_to_cwd)}")

    tag = f"[{status}]"

    if not use_color or not COLORAMA_AVAILABLE:
        return f"  {tag} {shown_path}"

    staged, unstaged = status[0], status[1]


    CONFLICT_CODES = {'UU', 'AA', 'DD', 'AU', 'UA', 'DU', 'UD'}

    if status in CONFLICT_CODES:
        color = Fore.RED
    elif status == "??":
        color = Fore.BLUE
    elif staged != " " and unstaged == " ":
        color = Fore.GREEN
    elif staged == " " and unstaged != " ":
        color = Fore.RED
    elif staged != " " and unstaged != " ":
        color = Fore.MAGENTA
    else:
        color = Style.RESET_ALL

    return f"{color}  {tag} {shown_path}{Style.RESET_ALL}"


def clutil_read_commit_message_file(file_path: str) -> str:
    """
    Reads a commit message from a file, with validation and processing.

    Args:
        file_path (str): Path to the file containing the commit message

    Returns:
        str: The commit message content

    Raises:
        OSError: If the file cannot be read
        ValueError: If the file is empty or contains only whitespace
    """
    try:
        # Resolve path relative to current working directory
        path = Path(file_path).resolve()

        # Basic security check - ensure file exists and is readable
        if not path.exists():
            raise OSError(f"File does not exist: {file_path}")

        if not path.is_file():
            raise OSError(f"Path is not a file: {file_path}")

        # Reasonable size limit for commit messages (generous 64KB)
        if path.stat().st_size > 64 * 1024:
            raise ValueError("Commit message file too large (>64KB)")

        # Read the file
        with open(path, 'r', encoding='utf-8') as f:
            content = f.read(64 * 1024)  # Enforce the same limit

    except (OSError, UnicodeDecodeError) as error:
        raise OSError(f"Cannot read file: {error}") from error

    # Validate content
    if not content or not content.strip():
        raise ValueError(
            "Commit message file is empty or contains only whitespace")

    # Process the content similar to how Git does it:
    # - Strip trailing whitespace from each line
    # - Remove trailing empty lines
    lines = [line.rstrip() for line in content.splitlines()]

    # Remove trailing empty lines
    while lines and not lines[-1]:
        lines.pop()

    if not lines:
        raise ValueError(
            "Commit message file contains no content after processing")

    # Join lines back together
    processed_content = '\n'.join(lines)

    return processed_content


def clutil_is_file_untracked_cached(
        file_path_rel_to_git_root: str,
        status_map: dict[str, str]) -> bool:
    """
    Check if a file is untracked using a precomputed status map.

    Looks the path up directly in the status map rather than shelling out
    to `git status` per file, which matters inside loops over changelist
    files. The caller is responsible for obtaining the status map once via
    clutil_get_file_status_map() before the loop.

    Args:
        file_path_rel_to_git_root: File path relative to git repository root
        status_map: Precomputed status map from clutil_get_file_status_map

    Returns:
        True if the file is untracked, False otherwise.
    """
    return status_map.get(file_path_rel_to_git_root, "  ") == "??"


def clutil_detect_merge_conflicts(status_map: dict[str, str]) -> list[str]:
    """
    Return a list of files currently in a merge-conflict (unmerged) state.

    Unmerged status codes per git-status(1):
      UU - both sides modified
      AA - both sides added
      DD - both sides deleted
      AU - added by us, modified by them
      UA - added by them, modified by us
      DU - deleted by us, modified by them
      UD - modified by us, deleted by them

    A file in any of these states cannot be safely staged, committed,
    stashed, or checked out via git-cl while the merge is unresolved.

    Args:
        status_map: Precomputed status map from clutil_get_file_status_map

    Returns:
        Sorted list of file paths (relative to git root) in a conflict state.
    """
    conflict_codes = {'UU', 'AA', 'DD', 'AU', 'UA', 'DU', 'UD'}
    return sorted(path for path, code in status_map.items()
                  if code in conflict_codes)


def clutil_refuse_on_merge_conflict(
        status_map: dict[str, str], operation: str) -> bool:
    """
    Check for merge conflicts and print a refusal message if any are found.

    Used at the top of state-mutating commands (stage, unstage, commit,
    stash, checkout) to bail out cleanly rather than letting git produce
    cryptic errors or leave the repo in an inconsistent state.

    Args:
        status_map: Precomputed status map from clutil_get_file_status_map
        operation: Short verb for the error message (e.g. 'stage', 'commit')

    Returns:
        True if a conflict was detected and the caller should return.
        False if the caller may proceed.
    """
    conflicts = clutil_detect_merge_conflicts(status_map)
    if not conflicts:
        return False

    clutil_print_error(f"Error: Cannot {operation} while merge conflicts are "
                       "unresolved.")
    clutil_print_error("The following files have conflicts:")
    for path in conflicts:
        clutil_print_error(f"  [{status_map[path]}] {path}")
    clutil_print_error("\nResolve conflicts first:")
    clutil_print_error("  1. Edit the files to resolve conflicts")
    clutil_print_error("  2. Mark them as resolved: git add <files>")
    operation_in_progress = clutil_git_operation_in_progress()
    if operation_in_progress == "merge":
        clutil_print_error("  3. Complete the merge: git commit")
        clutil_print_error("\nOr abort the merge: git merge --abort")
    elif operation_in_progress:
        clutil_print_error(f"  3. Continue the {operation_in_progress}, or "
                           "abort it (see 'git status')")
    return True


def clutil_refuse_on_intent_to_add(status_map: dict[str, str],
                                   git_root: Path) -> bool:
    """
    Refuse to stash while files are marked with 'git add -N'.

    Git cannot stash at all while the index holds such an entry, even for
    other paths ("Entry ... not uptodate. Cannot merge."). Returns True if
    the caller should stop.
    """
    marked = sorted(path for path, code in status_map.items() if code == " A")
    if not marked:
        return False
    cwd = Path.cwd().resolve()
    clutil_print_error("Error: Git cannot stash while files are marked with "
                       "'git add -N':")
    for path in marked:
        clutil_print_error(f"  [ A] {_relpath(git_root / path, cwd)}")
    paths = clutil_shell_paths(marked, git_root)
    clutil_print_error(f"Add them (git add {paths}) or unmark them "
                       f"(git rm --cached {paths}), then try again.")
    return True


def clutil_git_operation_in_progress() -> Optional[str]:
    """
    Tell which Git operation, if any, has stopped with conflicts.

    Conflicts can also come from 'git stash apply' or 'git cl unstash',
    which leave no operation to complete or abort. Hints for 'git commit'
    or 'git merge --abort' would be wrong then.

    Returns:
        "merge", "rebase", "cherry-pick" or "revert", or None if no such
        operation is in progress.
    """
    markers = [("MERGE_HEAD", "merge"), ("rebase-merge", "rebase"),
               ("rebase-apply", "rebase"), ("CHERRY_PICK_HEAD", "cherry-pick"),
               ("REVERT_HEAD", "revert")]
    for marker, operation in markers:
        try:
            path = subprocess.run(["git", "rev-parse", "--git-path", marker],
                                  check=True, capture_output=True,
                                  text=True).stdout.strip()
        except subprocess.CalledProcessError:
            return None
        if path and os.path.exists(path):
            return operation
    return None


def clutil_resolve_changelist_names(
        names: list[str], changelists: dict[str, list[str]],
        operation: str) -> Optional[list[str]]:
    """
    Validate changelist names for commands that act on several
    changelists at once (stage, unstage, commit).

    Duplicate names are dropped while preserving the user's order. If any
    name does not exist, an error is printed for each missing name and
    None is returned so that the caller changes nothing at all.

    Args:
        names: Changelist names as given on the command line
        changelists: Loaded changelist data
        operation: Past participle for the abort message (e.g. 'staged')

    Returns:
        The de-duplicated list of names, or None if any name is missing.
    """
    unique_names = list(dict.fromkeys(names))
    missing = [name for name in unique_names if name not in changelists]
    if not missing:
        return unique_names

    for name in missing:
        clutil_print_error(f"Error: Changelist '{name}' not found.")
    if len(unique_names) > 1:
        clutil_print_error(f"Nothing {operation}.")
    return None


def clutil_hint_untracked(names: list[str],
                          changelists: dict[str, list[str]],
                          status_map: dict[str, str]) -> None:
    """Point out that untracked files of the changelists need 'git add'."""
    untracked = [path for name in names for path in changelists[name]
                 if clutil_is_file_untracked_cached(path, status_map)]
    if untracked:
        paths = clutil_shell_paths(untracked, clutil_get_git_root())
        print(f"Untracked files are left out until you add them to Git: "
              f"git add {paths}")


def clutil_collect_changelist_files(
        names: list[str], changelists: dict[str, list[str]],
        git_root: Path, status_map: dict[str, str],
        include: Callable[[str], bool]) -> tuple[list[str],
                                                   dict[str, list[str]]]:
    """
    Collect existing files from one or more changelists, as paths relative
    to the current working directory, filtered by a predicate.

    Files that no longer exist are only included if Git reports a status
    for them, i.e. a deletion still to be committed. Files that are gone
    with no Git status (e.g. already committed as deleted) produce a
    warning and are skipped. A file listed in more than one changelist is
    only returned once.

    Args:
        names: Changelist names to collect from
        changelists: Loaded changelist data
        git_root: Repository root
        status_map: Precomputed status map from clutil_get_file_status_map
        include: Called with the stored path (relative to git root);
                 return True to include the file

    Returns:
        A tuple of (all files in order, files grouped by changelist name).
    """
    cwd = Path.cwd().resolve()
    files: list[str] = []
    files_by_name: dict[str, list[str]] = {}

    for name in names:
        files_by_name[name] = []
        for stored_path in changelists[name]:
            abs_path = clutil_resolve_file(git_root / stored_path)

            if not clutil_path_exists(abs_path) and stored_path not in status_map:
                clutil_print_error(f"Warning: '{stored_path}' does not exist.")
                continue

            rel_to_cwd = _relpath(abs_path, cwd)
            if include(stored_path) and rel_to_cwd not in files:
                files.append(rel_to_cwd)
                files_by_name[name].append(rel_to_cwd)

    return files, files_by_name


def clutil_changelist_label(names: list[str]) -> str:
    """
    Format changelist names for messages, e.g. "changelist 'a'" or
    "changelists 'a', 'b'".
    """
    quoted = ", ".join(f"'{name}'" for name in names)
    plural = "s" if len(names) > 1 else ""
    return f"changelist{plural} {quoted}"


def clutil_print_files_by_changelist(
        heading: str, names: list[str], files: list[str],
        files_by_name: dict[str, list[str]]) -> None:
    """
    Print the result of a stage, unstage or commit operation.

    For a single changelist the files are listed directly; for several
    changelists they are grouped by changelist name.

    Args:
        heading: Leading text, e.g. "Staged tracked files from"
        names: Changelist names involved
        files: All files that were processed
        files_by_name: Files grouped by changelist name
    """
    print(f"{heading} {clutil_changelist_label(names)}:")
    if len(names) == 1:
        for file in files:
            print(f"  {file}")
        return

    for name in names:
        print(f"  {name}:")
        if files_by_name[name]:
            for file in files_by_name[name]:
                print(f"    {file}")
        else:
            print("    (no files)")


def clutil_get_stash_file() -> Path:
    """
    Returns the path to the stash metadata file inside the Git directory.

    Returns:
        Path: Path to the '.git/cl-stashes.json' file.
    """
    git_dir = Path(subprocess.check_output(
        ["git", "rev-parse", "--git-dir"],
        stderr=subprocess.DEVNULL,
        text=True
    ).strip())
    return git_dir / "cl-stashes.json"


def clutil_load_stashes() -> dict[str, dict]:
    """
    Loads stash metadata from the 'cl-stashes.json' file.

    Returns:
        dict: A mapping of stashed changelist names to their metadata.

    Raises:
        ClutilLoadError: If the file exists but cannot be used. The reason
            has already been printed.
    """
    stash_file = clutil_get_stash_file()
    lock_file = stash_file.with_suffix('.lock')
    if stash_file.exists():
        with clutil_file_lock(lock_file):
            return clutil_read_json_file(stash_file, clutil_check_stash_data)
    return {}


def clutil_save_stashes(data: dict[str, dict]) -> None:
    """
    Saves the stash metadata to 'cl-stashes.json'.

    Writes are atomic: the data is first written to a temporary file in the
    same directory, then renamed over the target. If the process is
    interrupted mid-write, the original file is left untouched.

    Args:
        data (dict): Mapping of stashed changelist names to metadata.

    Raises:
        ClutilSaveError: If the file cannot be written. The error has
            already been printed.
    """
    stash_file = clutil_get_stash_file()
    lock_file = stash_file.with_suffix('.lock')
    with clutil_file_lock(lock_file):
        tmp_path = None
        try:
            fd, tmp_path = tempfile.mkstemp(
                dir=stash_file.parent,
                prefix='.cl-stashes.json.',
                suffix='.tmp'
            )
            with os.fdopen(fd, 'w', encoding='utf-8') as file_handle:
                json.dump(data, file_handle, indent=2)
            os.replace(tmp_path, stash_file)
            tmp_path = None
        except OSError as error:
            clutil_print_error(f"Error saving stash metadata: {error}")
            raise ClutilSaveError(str(error)) from error
        finally:
            if tmp_path is not None:
                try:
                    os.unlink(tmp_path)
                except OSError:
                    pass


# Git status analysis for unstash conflicts
# Maps (staged_char, unstaged_char) -> (is_conflict, description)
UNSTASH_STATUS_ANALYSIS = {
    ('?', '?'): (True, "untracked file blocking stash restoration"),
    (' ', 'M'): (True, "modified in working directory"),
    (' ', 'D'): (True, "deleted in working directory"),
    ('A', ' '): (False, "staged for addition (safe)"),
    ('M', ' '): (False, "staged modifications (safe)"),
    ('D', ' '): (False, "staged for deletion (safe)"),
    ('R', ' '): (False, "staged rename (safe)"),
    (' ', ' '): (False, "clean (ready for unstash)"),
}


def clutil_analyze_file_status_for_unstash(status: str) -> tuple[bool, str]:
    """
    Analyse a Git status code to determine unstash conflicts.

    Args:
        status: 2-character Git status code

    Returns:
        Tuple of (is_conflict, description)
    """
    if len(status) != 2:
        return False, "unknown status"

    staged, unstaged = status[0], status[1]

    # Check direct lookup first
    if (staged, unstaged) in UNSTASH_STATUS_ANALYSIS:
        return UNSTASH_STATUS_ANALYSIS[(staged, unstaged)]

    # Handle remaining cases with simple logic
    if unstaged in ['M', 'D']:
        if unstaged == 'M':
            conflict_desc = "modified in working directory"
        else:
            conflict_desc = "deleted in working directory"
        return True, conflict_desc

    if staged in ['A', 'M', 'D', 'R']:
        stage_desc = {
            'A': "staged for addition (safe)",
            'M': "staged modifications (safe)",
            'D': "staged for deletion (safe)",
            'R': "staged rename (safe)"
        }
        return False, stage_desc.get(staged, "staged changes (safe)")

    return False, "clean (ready for unstash)"


def clutil_check_unstash_conflicts_optimized(
        files: list[str], git_root: Path) -> tuple[list[str], dict[str, str]]:
    """
    Check for conflicts optimised for the stash-branch-unstash workflow.

    In the intended workflow:
    1. Stash changelists → clean working directory
    2. Create/switch to feature branch
    3. Unstash specific changelist → should be conflict-free

    This function focuses on detecting only the conflicts that actually matter
    in this workflow, rather than being overly conservative.

    Args:
        files: List of file paths relative to git root that were stashed
        git_root: Path to git repository root

    Returns:
        tuple: (real_conflicts, file_status_info) where:
        - real_conflicts: Files that will actually prevent unstashing
        - file_status_info: Dict of file -> status description for user info
    """
    status_map = clutil_get_file_status_map()
    real_conflicts = []
    file_status_info = {}

    for file_path in files:
        abs_path = clutil_resolve_file(git_root / file_path)

        if not clutil_path_exists(abs_path):
            # File doesn't exist - this is actually GOOD for unstashing
            # The stash will restore it without conflict
            file_status_info[file_path] = "missing (will be restored)"
            continue

        rel_to_git_root = abs_path.relative_to(git_root).as_posix()
        status = status_map.get(rel_to_git_root, "  ")

        # Use the lookup table for clean analysis
        is_conflict, description = clutil_analyze_file_status_for_unstash(status)

        if is_conflict:
            real_conflicts.append(file_path)

        file_status_info[file_path] = description

    return real_conflicts, file_status_info


def clutil_shell_paths(paths: list[str], git_root: Path) -> str:
    """Quote stored paths for a suggested command run in the current directory."""
    cwd = Path.cwd().resolve()
    return " ".join(shlex.quote(_relpath(git_root / path, cwd)) for path in paths)


def clutil_get_current_branch() -> Optional[str]:
    """
    Get the name of the current Git branch.

    Returns:
        Branch name or None if not on a branch (detached HEAD)
    """
    try:
        result = subprocess.run(["git", "branch", "--show-current"],
                                capture_output=True, text=True, check=True)
        branch = result.stdout.strip()
        return branch if branch else None
    except subprocess.CalledProcessError:
        return None


@contextmanager
def clutil_safe_stash_context(
        git_root: Path,
        files_for_git: list[str],
        untracked_files_for_git: list[str]) -> Iterator[tuple[list[str],
                                                              list[str]]]:
    """
    Context manager to handle directory changes during stash operations.
    Recalculates file paths relative to git root.

    Args:
        git_root: Path to git repository root
        files_for_git: Original file paths relative to current directory
        untracked_files_for_git: Original untracked file paths
                                 relative to current directory

    Yields:
        tuple[list[str], list[str]]: (files_for_git, untracked_files_for_git)
                                     relative to git root
    """
    original_cwd = Path.cwd().resolve()

    def convert_to_git_root_relative(file_paths: list[str]) -> list[str]:
        """Convert file paths to be relative to git root."""
        result = []
        for file_path in file_paths:
            abs_path = clutil_resolve_file(original_cwd / file_path)
            try:
                git_root_relative = abs_path.relative_to(git_root)
                result.append(git_root_relative.as_posix())
            except ValueError:
                # Path is outside git root - should not happen with validation
                result.append(file_path)
        return result

    # Convert both file lists
    safe_files = convert_to_git_root_relative(files_for_git)
    safe_untracked_files = convert_to_git_root_relative(untracked_files_for_git)

    # Change to git root
    os.chdir(git_root)

    try:
        yield safe_files, safe_untracked_files
    finally:
        # Try to restore original directory
        if original_cwd.exists():
            os.chdir(original_cwd)
        else:
            # Directory was deleted - warn user and stay in git root
            try:
                rel_path = _relpath(original_cwd, git_root)
                print(f"Note: Directory '{rel_path}' was removed by git stash.")
                print("Your shell is still pointing to the deleted directory.")
                print("Please run: cd ..")
            except (ValueError, OSError):
                print("Note: Your working directory was removed by git stash.")
                print("Your shell is still pointing to the deleted directory.")
                print("Please run: cd ..")


def clutil_get_stash_source_branch(stash_data: dict) -> Optional[str]:
    """
    Extract the branch name from stash metadata if stored.

    Args:
        stash_data: Stash metadata dictionary

    Returns:
        Branch name or None if not available
    """
    return stash_data.get('source_branch')


def clutil_create_unique_stash_message(changelist_name: str) -> str:
    """
    Create a unique stash message that includes changelist name and timestamp.
    This helps identify our stashes even when mixed with user-created stashes.

    Args:
        changelist_name: Name of the changelist being stashed

    Returns:
        Unique stash message string
    """
    timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
    return f"git-cl-stash:{changelist_name}:{timestamp}"


def clutil_list_stash_entries() -> Optional[list[tuple[str, str, str]]]:
    """
    List the entries of 'git stash list' with their commit hashes.

    Returns:
        A list of (reference, commit hash, reflog subject) tuples, newest
        first, e.g. ("stash@{0}", "3f2a…", "On main: git-cl-stash:one:…"),
        or None if 'git stash list' fails.
    """
    try:
        output = subprocess.run(
            ["git", "stash", "list", "--format=%gd%x00%H%x00%gs"],
            check=True, capture_output=True, text=True).stdout
    except (subprocess.CalledProcessError, OSError):
        return None
    entries = []
    for line in output.splitlines():
        parts = line.split("\0")
        if len(parts) == 3:
            entries.append((parts[0], parts[1], parts[2]))
    return entries


def clutil_stash_entry_matches(
    entry: tuple[str, str, str],
    record: dict,
    name: str
) -> bool:
    """
    Tell whether a 'git stash list' entry is the stash of a record.

    The stash commit hash recorded when the changelist was stashed
    identifies the stash exactly. Records from earlier versions have no
    hash; for them the full stash message 'git-cl-stash:<name>:<timestamp>'
    is matched, or, for the earliest records without a message, the
    prefix 'git-cl-stash:<name>:'.

    The message alone is not unique: worktrees of one repository share
    the stash list, so a changelist of the same name stashed in another
    worktree within the same second has the same message.

    Args:
        entry: (reference, commit hash, reflog subject) from
            clutil_list_stash_entries()
        record: The stash record from cl-stashes.json
        name: The changelist name the record is stored under

    Returns:
        True if the entry belongs to the record's stash.
    """
    _, commit, subject = entry
    stash_commit = record.get("stash_commit")
    if isinstance(stash_commit, str) and stash_commit:
        return commit == stash_commit
    message = record.get("stash_message")
    if isinstance(message, str) and message:
        return subject.endswith(": " + message)
    return f"git-cl-stash:{name}:" in subject


def clutil_find_stash_ref(record: dict, name: str) -> Optional[str]:
    """
    Find the current reference of a record's stash in 'git stash list'.

    The reference shifts (stash@{0} becomes stash@{1}) whenever another
    stash is pushed, so it is looked up each time.

    Args:
        record: The stash record from cl-stashes.json
        name: The changelist name the record is stored under

    Returns:
        The stash reference (e.g. "stash@{2}") or None if not found
    """
    for entry in clutil_list_stash_entries() or []:
        if clutil_stash_entry_matches(entry, record, name):
            return entry[0]
    return None


def clutil_find_orphaned_stashes(stashes: dict[str, dict]) -> list[str]:
    """
    Find stashed changelists whose Git stash no longer exists.

    A record is orphaned when no entry in 'git stash list' belongs to it
    (see clutil_stash_entry_matches()). This happens when the stash was
    popped or dropped with plain git. Such a record can never be
    unstashed, and its files cannot be added to another changelist.

    Args:
        stashes: Stashed changelists as loaded by clutil_load_stashes()

    Returns:
        Sorted names of orphaned records. Empty if 'git stash list' fails,
        so that a Git error never makes records look orphaned.
    """
    if not stashes:
        return []
    entries = clutil_list_stash_entries()
    if entries is None:
        return []
    return sorted(name for name, record in stashes.items()
                  if not any(clutil_stash_entry_matches(entry, record, name)
                             for entry in entries))


def clutil_print_orphaned_stash_hint(name: str) -> None:
    """Explain that a stash record is orphaned and how to remove it."""
    clutil_print_error(f"The stash of changelist '{name}' no longer exists. "
                       "It was probably popped or")
    clutil_print_error("dropped with plain git. Run 'git cl prune' to remove "
                       "its record.")


def clutil_stash_all_changelists(changelists: dict[str, list[str]],
                                 quiet: bool = False) -> tuple[int, int]:
    """
    Helper function to stash all active changelists.

    Args:
        changelists: Dictionary of active changelists
        quiet: If True, suppress verbose output for workflow contexts

    Returns:
        Tuple of (success_count, total) where total is the number of
        non-empty changelists. Callers must compare the two to detect
        partial failures (see issue #51).
    """
    if not changelists:
        if not quiet:
            print("No active changelists found.")
        return 0, 0

    success_count = 0

    # Sort changelists by name for predictable order
    sorted_changelists = sorted(changelists.items())
    total = len([cl for cl, files in sorted_changelists if files])

    for cl_name, files in sorted_changelists:
        if not files:  # Skip empty changelists
            continue

        # Create a temporary args object for individual stash
        temp_args = argparse.Namespace()
        temp_args.name = cl_name
        temp_args.all = False

        try:
            # Call cl_stash with quiet mode. cl_stash reports its own
            # errors and returns False on failure, so only count real
            # successes here (previously every call was counted).
            if cl_stash(temp_args, quiet=quiet):
                success_count += 1
            else:
                clutil_print_error(f"Changelist '{cl_name}' was not stashed.")
        except (OSError, subprocess.CalledProcessError,
                json.JSONDecodeError) as error:
            clutil_report_failure(f"Could not stash changelist '{cl_name}'",
                                  error)
            continue

    if not quiet and success_count < total:
        clutil_print_error(f"Error: Only {success_count}/{total} changelists "
                           "could be stashed.")

    return success_count, total


def clutil_validate_stash_preconditions(
    name: str,
    changelists: dict[str, list[str]],
    stashes: dict[str, dict]
) -> Optional[str]:
    """
    Validate preconditions for stashing a changelist.

    Args:
        name: Changelist name
        changelists: Active changelists
        stashes: Already stashed changelists

    Returns:
        Error message if validation fails, None if all checks pass
    """
    # Check if changelist is already stashed
    if name in stashes:
        return (f"Error: Changelist '{name}' is already stashed.\n"
                f"Restore it with: git cl unstash {name}")

    # Check if changelist exists
    if name not in changelists:
        return f"Error: Changelist '{name}' not found."

    # Check if changelist is empty
    if not changelists[name]:
        return f"Error: Changelist '{name}' is empty - nothing to stash."

    return None


def clutil_categorize_files_for_stash(
    files: list[tuple[str, Path]],
    missing_files: list[str],
    status_map: dict[str, str],
    git_root: Path
) -> tuple[dict[str, list[str]], list[str], list[str]]:
    """
    Categorize files based on their Git status for stashing.

    Args:
        files: List of (stored_path, abs_path) tuples for existing files
        missing_files: List of paths for non-existent files
        status_map: Git status mapping
        git_root: Git repository root

    Returns:
        Tuple of (file_categories, stashable_files, unstashable_files)
    """
    file_categories: dict[str, list[str]] = {
        'unstaged_changes': [],     # Modified, deleted in working directory
        'staged_additions': [],     # Newly added to index (A_)
        'untracked': [],            # Untracked files (??)
        'deleted_files': [],        # Files that don't exist (potential deletions)
        'clean_files': [],          # Clean files (not stashable)
        'staged_modifications': []  # Files with only staged changes (not stashable)
    }

    stashable_files = []
    unstashable_files = []

    # Process existing files
    for stored_path, abs_path in files:
        rel_to_git_root = abs_path.relative_to(git_root).as_posix()
        status = status_map.get(rel_to_git_root, "  ")
        staged, unstaged = status[0], status[1]

        if status == "??":
            # Untracked files
            # - stashable since they're explicitly in changelist
            file_categories['untracked'].append(stored_path)
            stashable_files.append(stored_path)
        elif unstaged in ['M', 'D']:
            # Unstaged modifications/deletions - stashable
            file_categories['unstaged_changes'].append(stored_path)
            stashable_files.append(stored_path)
        elif staged == 'A' and unstaged == ' ':
            # Newly added to index - stashable
            file_categories['staged_additions'].append(stored_path)
            stashable_files.append(stored_path)
        elif staged in ['M', 'D', 'R'] and unstaged == ' ':
            # Only staged changes - not stashable with git stash push
            file_categories['staged_modifications'].append(stored_path)
            unstashable_files.append(stored_path)
        elif status == "  ":
            # Clean files - not stashable
            file_categories['clean_files'].append(stored_path)
            unstashable_files.append(stored_path)
        else:
            # Mixed staged+unstaged or other complex states
            if unstaged != ' ':
                # Has unstaged component - stashable
                file_categories['unstaged_changes'].append(stored_path)
                stashable_files.append(stored_path)
            else:
                # Only staged component - not stashable
                file_categories['staged_modifications'].append(stored_path)
                unstashable_files.append(stored_path)

    # Process missing files (potential deletions)
    for stored_path in missing_files:
        # Check if this is a deletion by looking at git status
        rel_to_git_root = stored_path  # already relative to git root
        status = status_map.get(rel_to_git_root, "  ")

        if status[1] == 'D':  # Deleted in working directory
            file_categories['deleted_files'].append(stored_path)
            stashable_files.append(stored_path)
        else:
            # File just doesn't exist and git doesn't know about it
            clutil_print_error(f"Warning: File '{stored_path}' "
                               f"does not exist and is not tracked.")
            unstashable_files.append(stored_path)

    return file_categories, stashable_files, unstashable_files


def clutil_report_stash_categorization(
    file_categories: dict[str, list[str]],
    unstashable_files: list[str],
    name: str
) -> bool:
    """
    Report file categorization results and check if stash can proceed.

    Args:
        file_categories: Categorized files
        unstashable_files: List of unstashable files
        name: Changelist name

    Returns:
        True if stash can proceed, False otherwise
    """
    # Check for unstashable files and report (always show errors)
    if unstashable_files:
        clutil_print_error(f"\nError: Cannot stash changelist '{name}' "
                           f"because these files are not stashable:")

        if file_categories['clean_files']:
            clutil_print_error("  Clean files (no changes):")
            for file_path in file_categories['clean_files']:
                clutil_print_error(f"    {file_path}")

        if file_categories['staged_modifications']:
            clutil_print_error("  Files with only staged changes:")
            for file_path in file_categories['staged_modifications']:
                clutil_print_error(f"    {file_path}")

        other_unstashable = [f for f in unstashable_files
                             if f not in file_categories['clean_files']
                             and f not in file_categories['staged_modifications']]
        if other_unstashable:
            clutil_print_error("  Other non-stashable files:")
            for file_path in other_unstashable:
                clutil_print_error(f"    {file_path}")

        clutil_print_error("\nA file can be stashed if it:")
        clutil_print_error("  - has unstaged changes (modified or deleted)")
        clutil_print_error("  - is newly added to the index")
        clutil_print_error("  - is untracked")
        if file_categories['staged_modifications']:
            clutil_print_error(f"Unstage them first: git cl unstage {name}")
        if file_categories['clean_files']:
            clutil_print_error(
                "Remove files without changes: git cl rm "
                f"{clutil_shell_paths(file_categories['clean_files'], clutil_get_git_root())}")
        return False

    return True


def clutil_prepare_files_for_git_stash(
    stashable_files: list[str],
    file_categories: dict[str, list[str]],
    git_root: Path
) -> tuple[list[str], list[str]]:
    """
    Prepare file paths for git stash command.

    Args:
        stashable_files: List of files to stash
        file_categories: Categorized files
        git_root: Git repository root

    Returns:
        Tuple of (files_for_git, untracked_files_for_git)
    """
    files_for_git = []
    for stored_path in stashable_files:
        abs_path = clutil_resolve_file(git_root / stored_path)
        if clutil_path_exists(abs_path):
            rel_to_cwd = _relpath(abs_path, Path.cwd().resolve())
            files_for_git.append(rel_to_cwd)
        else:
            # For deleted files, we still need to pass the path
            rel_to_cwd = _relpath(git_root / stored_path, Path.cwd().resolve())
            files_for_git.append(rel_to_cwd)

    # Handle untracked files specially
    # - they need to be added to git first for stashing
    untracked_files_for_git = []
    if file_categories['untracked']:
        for stored_path in file_categories['untracked']:
            abs_path = clutil_resolve_file(git_root / stored_path)
            rel_to_cwd = _relpath(abs_path, Path.cwd().resolve())
            untracked_files_for_git.append(rel_to_cwd)

        try:
            # Add untracked files to git index
            subprocess.run(["git", "add", "--"]
                           + clutil_literal_pathspecs(untracked_files_for_git),
                           check=True)
        except subprocess.CalledProcessError as error:
            clutil_report_failure("Could not add untracked files for stashing",
                                  error)
            raise

    return files_for_git, untracked_files_for_git


def clutil_execute_git_stash(
    name: str,
    stash_message: str,
    files_for_git: list[str],
    untracked_files_for_git: list[str]
) -> str:
    """
    Execute the git stash command.

    Args:
        name: Changelist name (used to locate the created stash)
        stash_message: Pre-generated unique stash message, shared with the
            metadata save so the two can never diverge across a second boundary
        files_for_git: Files to stash
        untracked_files_for_git: Untracked files that were temporarily added

    Returns:
        The stash reference if successful

    Raises:
        subprocess.CalledProcessError: If stash fails
    """

    try:
        cmd = (["git", "stash", "push", "-m", stash_message, "--"]
               + clutil_literal_pathspecs(files_for_git))
        result = subprocess.run(cmd, capture_output=True, text=True, check=True)

        # Check if anything was actually stashed
        if "No local changes to save" in result.stderr:
            clutil_print_error("Error: Git stashed no changes for changelist "
                               f"'{name}'.")
            # If we added untracked files, we should reset them
            if untracked_files_for_git:
                try:
                    subprocess.run(["git", "reset", "--quiet", "HEAD", "--"] +
                                   clutil_literal_pathspecs(
                                       untracked_files_for_git), check=True)
                    clutil_print_error("Reset temporarily added untracked files.")
                except subprocess.CalledProcessError:
                    clutil_print_error("Warning: Could not reset temporarily added "
                                       "untracked files.")
            raise ValueError("No changes were stashed")

    except subprocess.CalledProcessError as error:
        clutil_report_failure(f"Could not stash changelist '{name}'", error)

        # Cleanup: Reset any untracked files we added
        if untracked_files_for_git:
            try:
                subprocess.run(["git", "reset", "--quiet", "HEAD", "--"]
                               + clutil_literal_pathspecs(untracked_files_for_git),
                               check=True)
                clutil_print_error("Reset temporarily added untracked files after "
                                   "stash failure.")
            except subprocess.CalledProcessError:
                clutil_print_error("Warning: Could not reset temporarily added "
                                   "untracked files.")
        raise

    # Find the created stash. It is the newest one, so refs/stash points
    # to it; its commit hash identifies it even if another stash has the
    # same message.
    try:
        stash_commit = subprocess.run(
            ["git", "rev-parse", "--verify", "--quiet", "refs/stash"],
            check=True, capture_output=True, text=True).stdout.strip()
    except subprocess.CalledProcessError:
        stash_commit = ""
    stash_ref = clutil_find_stash_ref(
        {"stash_commit": stash_commit, "stash_message": stash_message}, name)
    if not stash_ref:
        clutil_print_error("Error: Could not locate the created stash.")
        clutil_print_error("Look for a stash with message containing "
                           f"'git-cl-stash:{name}:'")
        raise ValueError("Could not locate stash")

    return stash_ref


def clutil_build_stash_metadata(
    stash_message: str,
    stash_ref: str,
    files: list[str],
    file_categories: dict[str, list[str]],
    current_branch: Optional[str]
) -> dict:
    """
    Build stash metadata dictionary.

    Args:
        stash_message: Pre-generated unique stash message — the same string
            passed to `git stash push`, so metadata and git never diverge
        stash_ref: Git stash reference
        files: Files in the changelist
        file_categories: Categorized files
        current_branch: Current Git branch

    Returns:
        Dictionary containing stash metadata. 'stash_commit' is the commit
        hash of the stash, which identifies it exactly; it is left out if
        it cannot be determined.
    """
    try:
        stash_commit = subprocess.run(
            ["git", "rev-parse", "--verify", "--quiet", stash_ref],
            check=True, capture_output=True, text=True).stdout.strip()
    except subprocess.CalledProcessError:
        stash_commit = ""
    metadata = {
        "stash_ref": stash_ref,
        "stash_message": stash_message,
        "files": files.copy(),
        "timestamp": datetime.datetime.now().isoformat(),
        "source_branch": current_branch,
        "file_categories": {
            "unstaged_changes": file_categories['unstaged_changes'],
            "staged_additions": file_categories['staged_additions'],
            "untracked": file_categories['untracked'],
            "deleted_files": file_categories['deleted_files']
        }
    }
    if stash_commit:
        metadata["stash_commit"] = stash_commit
    return metadata


# pylint: disable-next=too-many-arguments
def clutil_save_stash_metadata_atomic(
    name: str,
    stash_message: str,
    stash_ref: str,
    files: list[str],
    file_categories: dict[str, list[str]],
    changelists: dict[str, list[str]],
    stashes: dict[str, dict]
) -> None:
    """
    Atomically save stash metadata and update changelists.

    The stash metadata is written first, then the changelist is removed
    from 'cl.json'. If the second write fails, the stash entry is removed
    again, so that on failure both files are left as they were.

    Args:
        name: Changelist name
        stash_message: Pre-generated unique stash message (shared with the
            git stash push call)
        stash_ref: Git stash reference
        files: Files in the changelist
        file_categories: Categorized files
        changelists: Active changelists (will be modified)
        stashes: Stashed changelists (will be modified)

    Raises:
        ClutilSaveError: If either file cannot be written.
    """
    current_branch = clutil_get_current_branch()

    # Build stash metadata
    stash_metadata = clutil_build_stash_metadata(
        stash_message, stash_ref, files, file_categories, current_branch
    )

    # Save stash metadata. If this fails, nothing has been written yet.
    stashes[name] = stash_metadata
    try:
        clutil_save_stashes(stashes)
    except ClutilSaveError:
        del stashes[name]
        raise

    # Remove changelist from active changelists
    files_in_changelist = changelists.pop(name)
    try:
        clutil_save(changelists)
    except ClutilSaveError:
        changelists[name] = files_in_changelist
        del stashes[name]
        try:
            clutil_save_stashes(stashes)
        except ClutilSaveError:
            clutil_print_error(f"Warning: Could not remove the stash entry for "
                               f"'{name}' from the stash metadata.")
        raise


def clutil_restore_index_from_stash(
    stash_ref: str,
    files: list[str],
    untracked_files: list[str],
    git_root: Path
) -> list[str]:
    """
    Restore the staged part of stashed files after 'git stash apply'.

    Applying a stash without --index leaves all changes unstaged, except
    new files, which are staged. 'git stash apply --index' cannot be used
    instead: a stash limited to some paths still records the whole index,
    so it fails as soon as files outside the changelist are staged as new
    files. This function therefore restores the index per file:

    - Files whose index differed from HEAD when they were stashed get
      their index entry back from the stash's index commit (<stash>^2).
      This is only done if the file is unchanged between the commit the
      stash was made on (<stash>^1) and the current HEAD. Otherwise the
      staged content would belong to another base, and the file is left
      unstaged.
    - Files that were untracked before stashing had to be added to the
      index temporarily. They are unstaged again.

    Args:
        stash_ref: Git stash reference, not yet dropped
        files: Files of the changelist, relative to the Git root
        untracked_files: Files that were untracked when stashed,
            relative to the Git root
        git_root: Path to the Git repository root

    Returns:
        list[str]: Files whose staged changes could not be restored and
            are now unstaged. Empty if all were restored.

    Raises:
        subprocess.CalledProcessError: If a Git command fails.
    """
    git = ["git", "-C", str(git_root)]
    untracked = set(untracked_files)

    staged = subprocess.run(
        git + ["diff", "--name-only", "-z", "--no-renames",
               f"{stash_ref}^1", f"{stash_ref}^2", "--"]
        + clutil_literal_pathspecs(files),
        check=True, capture_output=True, text=True).stdout
    staged_files = [f for f in staged.split("\0") if f and f not in untracked]

    def blob(revision: str, path: str) -> Optional[str]:
        result = subprocess.run(git + ["rev-parse", "--verify", "--quiet",
                                       f"{revision}:{path}"],
                                capture_output=True, text=True, check=False)
        return result.stdout.strip() if result.returncode == 0 else None

    to_restore = []
    not_restored = []
    for path in staged_files:
        if blob(f"{stash_ref}^1", path) == blob("HEAD", path):
            to_restore.append(path)
        else:
            not_restored.append(path)

    if to_restore:
        subprocess.run(git + ["reset", "--quiet", f"{stash_ref}^2", "--"]
                       + clutil_literal_pathspecs(to_restore),
                       check=True, capture_output=True, text=True)

    still_staged = [f for f in untracked_files
                    if (git_root / f).exists() or (git_root / f).is_symlink()]
    if still_staged:
        subprocess.run(git + ["reset", "--quiet", "--"]
                       + clutil_literal_pathspecs(still_staged),
                       check=True, capture_output=True, text=True)

    return not_restored


def clutil_restore_failed_stash(
    stash_ref: str,
    stashed_files: list[str],
    untracked_files: list[str],
    git_root: Path
) -> bool:
    """
    Restore the changes of a stash whose metadata could not be saved.

    Applies the stash, restores the staged part of its files with
    clutil_restore_index_from_stash() and drops it only once its changes
    are back.

    Args:
        stash_ref: Git stash reference created moments before
        stashed_files: Files passed to git stash, relative to the Git root
        untracked_files: Temporarily added files, relative to the Git root
        git_root: Path to the Git repository root

    Returns:
        True if the changes were restored, False if they remain in the stash.
    """
    git = ["git", "-C", str(git_root)]
    try:
        subprocess.run(git + ["stash", "apply", "--quiet", stash_ref],
                       check=True, capture_output=True, text=True)
    except subprocess.CalledProcessError:
        return False

    try:
        clutil_restore_index_from_stash(stash_ref, stashed_files,
                                        untracked_files, git_root)
    except subprocess.CalledProcessError:
        clutil_print_error("Warning: Your changes are back, but which of them "
                           "are staged may differ from before.")

    try:
        subprocess.run(git + ["stash", "drop", "--quiet", stash_ref],
                       check=True, capture_output=True, text=True)
    except subprocess.CalledProcessError:
        clutil_print_error(f"Warning: Could not drop {stash_ref}; its changes "
                           "are already restored.")
    return True


def clutil_handle_stash_failure(
    name: str,
    stash_ref: str,
    stash_message: str,
    stashed_files: list[str],
    untracked_files: list[str],
    git_root: Path
) -> None:
    """
    Handle a failed stash metadata save by restoring the stashed changes.

    By the time the metadata is saved, git stash has already removed the
    changes from the working directory, so the stash must be applied, not
    just dropped. The metadata itself needs no rollback here, because
    clutil_save_stash_metadata_atomic leaves both files unchanged when it
    fails.

    Args:
        name: Changelist name
        stash_ref: Git stash reference
        stash_message: Message of the stash, to help the user find it
        stashed_files: Files passed to git stash, relative to the Git root
        untracked_files: Temporarily added files, relative to the Git root
        git_root: Path to the Git repository root
    """
    clutil_print_error(f"Error: Could not save the stash of changelist '{name}'.")

    if clutil_restore_failed_stash(stash_ref, stashed_files, untracked_files,
                                   git_root):
        clutil_print_error(f"Your changes have been restored. Changelist '{name}' "
                           "remains active.")
    else:
        clutil_print_error("Your changes could not be restored automatically. "
                           "They are kept in")
        clutil_print_error(f"  {stash_ref} ({stash_message})")
        clutil_print_error(f"Restore them with: git stash pop {stash_ref}")
        if untracked_files:
            clutil_print_error("Previously untracked files will then be staged. "
                               "Unstage them with:")
            clutil_print_error("  git restore --staged -- "
                               + " ".join(untracked_files))


def clutil_unstash_all_changelists(
    stashes: dict[str, dict],
    force: bool = False
) -> tuple[int, int]:
    """
    Helper function to unstash all stashed changelists.

    Args:
        stashes: Dictionary of stashed changelists
        force: Whether to force unstash despite conflicts

    Returns:
        Tuple of (success_count, total). Callers must compare the two
        to detect partial failures.
    """
    if not stashes:
        print("No stashed changelists found.")
        return 0, 0

    current_branch = clutil_get_current_branch()
    if not current_branch:
        clutil_print_error("Error: Cannot unstash --all while in detached HEAD state.")
        clutil_print_error("Switch to a branch first: git checkout -b <branch-name>")
        return 0, len(stashes)

    success_count = 0

    # Sort by timestamp (oldest first) for predictable order
    stash_items = list(stashes.items())
    stash_items.sort(key=lambda x: x[1].get('timestamp', ''))

    for stash_name, _ in stash_items:
        # Create a temporary args object for individual unstash
        temp_args = argparse.Namespace()
        temp_args.name = stash_name
        temp_args.force = force
        temp_args.all = False

        try:
            # Note: cl_unstash is called later in the module. It reports
            # its own errors and returns False on failure, so only count
            # real successes here.
            if cl_unstash(temp_args):
                success_count += 1
            else:
                clutil_print_error(f"Changelist '{stash_name}' was not unstashed.")
        except (OSError,
                subprocess.CalledProcessError, json.JSONDecodeError) as error:
            clutil_report_failure(
                f"Could not unstash changelist '{stash_name}'", error)
            continue

    if success_count < len(stash_items):
        clutil_print_error(f"Error: Only {success_count}/{len(stash_items)} "
                           "changelists could be unstashed.")
    return success_count, len(stash_items)


def clutil_validate_unstash_preconditions(
    base_name: str,
    stash_key: str,
    stashes: dict[str, dict],
    changelists: dict[str, list[str]]
) -> Optional[str]:
    """
    Validate preconditions for unstashing a changelist.

    Args:
        base_name: The base changelist name
        stash_key: The key in stashes dictionary
        stashes: Dictionary of stashed changelists
        changelists: Dictionary of active changelists

    Returns:
        Error message if validation fails, None if all checks pass
    """
    if stash_key not in stashes:
        error_msg = f"Error: No stashed changelist found for '{base_name}'."
        available = list(stashes.keys())
        if available:
            error_msg += "\nAvailable stashed changelists:"
            for stashed_name in available:
                error_msg += f"\n  {stashed_name}"
        return error_msg

    # Check if target changelist name already exists
    if base_name in changelists and changelists[base_name]:
        return (f"Error: Changelist '{base_name}' already exists with files.\n"
                "Please delete or rename the existing changelist first.")

    return None


def clutil_check_branch_workflow(
    base_name: str,
    source_branch: Optional[str],
    force: bool,
    ignore_untracked: bool = False
) -> Optional[str]:
    """
    Check branch workflow requirements for unstashing.

    Args:
        base_name: The changelist name
        source_branch: The branch where changelist was stashed from
        force: Whether to force unstash despite warnings
        ignore_untracked: Whether untracked files may be present in an
            otherwise clean working directory. 'git cl br' sets this:
            untracked files outside any changelist are never stashed, so
            they follow the switch to the new branch, as with
            'git checkout -b'.

    Returns:
        Error message if check fails, None if checks pass
    """
    if force:
        return None

    current_branch = clutil_get_current_branch()

    if not current_branch:
        operation = clutil_git_operation_in_progress()
        if operation:
            return (f"Error: Cannot unstash while a {operation} is in "
                    "progress.\n"
                    f"Finish or abort the {operation} first (see 'git "
                    "status'), then unstash.\n"
                    f"Or use --force to unstash anyway: git cl unstash "
                    f"{base_name} --force")
        return ("Error: Cannot unstash while in detached HEAD state.\n"
                "Create a new branch first: git checkout -b feature-branch\n"
                f"Or use --force to unstash anyway: git cl unstash {base_name} --force")

    # Restoring to the original branch needs no further check
    if not source_branch or current_branch != source_branch:
        # Check if working directory is clean (recommended for branch
        # workflow). Uncommitted changes inside a submodule belong to the
        # submodule's own repository and are ignored.
        status_cmd = ["git", "status", "--porcelain",
                      "--ignore-submodules=dirty"]
        if ignore_untracked:
            status_cmd.append("--untracked-files=no")
        try:
            git_status = subprocess.run(status_cmd,
                                        capture_output=True, text=True, check=True)
            if git_status.stdout.strip():
                origin = (f"'{base_name}' was stashed on branch "
                          f"'{source_branch}'; unstashing"
                          if source_branch else "Unstashing")
                return (f"Error: Cannot unstash '{base_name}' onto branch "
                        f"'{current_branch}', which has uncommitted changes.\n"
                        f"{origin} it here would mix both pieces of work.\n"
                        f"Commit or stash the changes on '{current_branch}' "
                        "first, or unstash anyway: git cl unstash "
                        f"{base_name} --force")
        except subprocess.CalledProcessError:
            pass  # git status failed, continue anyway

    return None


def clutil_check_and_report_conflicts(
    files: list[str],
    git_root: Path,
    base_name: str,
    force: bool
) -> bool:
    """
    Check that unstashing would not overwrite local changes; report them.

    Args:
        files: List of files to unstash
        git_root: Git repository root
        base_name: Changelist name
        force: Whether to skip the check

    Returns:
        True if unstash can proceed, False otherwise
    """
    if force:
        return True

    real_conflicts, _ = clutil_check_unstash_conflicts_optimized(files, git_root)

    if real_conflicts:
        status_map = clutil_get_file_status_map()
        cwd = Path.cwd().resolve()
        clutil_print_error(f"Error: Cannot unstash '{base_name}': unstashing "
                           "would overwrite changes in these files:")
        for path in real_conflicts:
            clutil_print_error(f"  [{status_map.get(path, '  ')}] "
                               f"{_relpath(git_root / path, cwd)}")
        untracked = [p for p in real_conflicts if status_map.get(p) == "??"]
        tracked = [p for p in real_conflicts if p not in untracked]
        clutil_print_error("Commit or stash these changes first, or discard them:")
        hints = []
        if tracked:
            hints.append((f"git restore {clutil_shell_paths(tracked, git_root)}",
                          "discards your changes"))
        if untracked:
            hints.append((f"rm {clutil_shell_paths(untracked, git_root)}",
                          "deletes the untracked "
                          + ("file" if len(untracked) == 1 else "files")))
        width = max(len(command) for command, _ in hints)
        for command, effect in hints:
            clutil_print_error(f"  {command:<{width}}  # {effect}")
        clutil_print_error(f"Then run: git cl unstash {base_name}")
        return False

    return True


def clutil_verify_and_update_stash_ref(
    base_name: str,
    old_stash_ref: str,
    stash_data: dict
) -> Optional[str]:
    """
    Verify stash still exists and update reference if needed.

    Checks if the stash for the given changelist still exists and updates
    the stash reference if it has changed (due to other stash operations).
    The updated reference is persisted to the stash metadata file to prevent
    future reference drift.

    Args:
        base_name: Changelist name
        old_stash_ref: Previously stored stash reference
        stash_data: The stash record, used to find the stash

    Returns:
        Updated stash reference or None if stash doesn't exist
    """
    current_stash_ref = clutil_find_stash_ref(stash_data, base_name)

    if not current_stash_ref:
        clutil_print_error(f"Error: Stash for changelist '{base_name}' no longer "
                           "exists.")
        clutil_print_error("The stash may have been manually dropped. Available "
                           "stashes:")
        try:
            stash_list = subprocess.check_output(["git", "stash", "list"],
                                                 text=True)
            if stash_list.strip():
                for line in stash_list.strip().split('\n'):
                    clutil_print_error(f"  {line}")
            else:
                clutil_print_error("  (no stashes found)")
        except subprocess.CalledProcessError:
            clutil_print_error("  (could not list stashes)")
        clutil_print_error("Run 'git cl prune' to remove its record.")
        return None

    # Update stash reference if needed
    if current_stash_ref != old_stash_ref:
        # Persist the updated reference to prevent future drift
        stashes = clutil_load_stashes()
        if base_name in stashes:
            stashes[base_name]["stash_ref"] = current_stash_ref
            clutil_save_stashes(stashes)

    return current_stash_ref


def clutil_report_unstash_conflicts(stash_ref: str, base_name: str) -> None:
    """
    Explain what to do after 'git stash apply' stopped with conflicts.

    Args:
        stash_ref: Git stash reference, which is kept
        base_name: Changelist name
    """
    try:
        conflicted = subprocess.run(
            ["git", "diff", "--name-only", "--diff-filter=U", "-z"],
            check=True, capture_output=True, text=True).stdout.split("\0")
    except subprocess.CalledProcessError:
        conflicted = []
    git_root = clutil_get_git_root()
    cwd = Path.cwd().resolve()
    conflicted = [_relpath(git_root / f, cwd) for f in conflicted if f]

    clutil_print_error(f"Error: Unstashing '{base_name}' stopped with "
                       "conflicts in:")
    for path in conflicted:
        clutil_print_error(f"  {path}")
    clutil_print_error(f"Changelist '{base_name}' is restored, and its changes "
                       "are in the working directory,")
    clutil_print_error("with conflict markers in the files above. Edit them, "
                       "then mark them as resolved:")
    clutil_print_error("  git add " + " ".join(shlex.quote(p) for p in conflicted)
                       if conflicted else "  git add <files>")
    clutil_print_error(f"The stash is kept as {stash_ref} in case you need it. "
                       "Once you are done:")
    clutil_print_error(f"  git stash drop {stash_ref}")


def clutil_stash_for_files(stash_ref: str, files: list[str],
                           git_root: Path) -> str:
    """
    Returns a stash commit that holds only the changes of the given files.

    'git stash push -- <paths>' records the whole index: the index commit
    (<stash>^2) and the working-tree commit (<stash>) also contain files
    outside <paths> that were staged at the time. 'git stash apply' would
    apply those staged changes again, for example bring back a file
    deleted since then. This builds a copy of the stash whose trees equal
    the stash's base commit (<stash>^1) except for the given files, with
    the same parents, and returns it. The copy is an ordinary commit that
    'git stash apply' accepts; it is not added to the stash list.

    Args:
        stash_ref: Git stash reference
        files: Files of the changelist, relative to the Git root
        git_root: Path to the Git repository root
    Returns:
        str: The commit to apply; stash_ref itself if it holds nothing else.
    Raises:
        subprocess.CalledProcessError: If a Git command fails.
        OSError: If the temporary index cannot be created.
    """
    git = ["git", "-C", str(git_root)]

    def rev(spec: str) -> Optional[str]:
        result = subprocess.run(git + ["rev-parse", "--verify", "--quiet",
                                       spec],
                                capture_output=True, text=True, check=False)
        return result.stdout.strip() or None

    base = rev(f"{stash_ref}^1")
    index_commit = rev(f"{stash_ref}^2")
    if base is None or index_commit is None:
        return stash_ref
    untracked_commit = rev(f"{stash_ref}^3")

    git_dir = subprocess.run(git + ["rev-parse", "--absolute-git-dir"],
                             capture_output=True, text=True,
                             check=True).stdout.strip()
    handle, temp_index = tempfile.mkstemp(prefix="cl-index-", dir=git_dir)
    os.close(handle)
    env = {**os.environ, "GIT_INDEX_FILE": temp_index}

    def tree_with_files(commit: str) -> str:
        # Start from the base commit and take only the given files
        # from the commit
        os.unlink(temp_index)
        subprocess.run(git + ["read-tree", base], env=env, check=True,
                       capture_output=True, text=True)
        listing = subprocess.run(
            git + ["ls-tree", "-r", "-z", commit, "--"]
            + clutil_literal_pathspecs(files),
            check=True, capture_output=True, text=True).stdout
        # Each entry is "<mode> <type> <hash>\t<path>"
        entries = [e.split("\t", 1) for e in listing.split("\0") if e]
        present = {path for _, path in entries}
        absent = [f for f in files if f not in present]
        if absent:
            subprocess.run(git + ["update-index", "--force-remove", "-z",
                                  "--stdin"],
                           input="".join(f + "\0" for f in absent), env=env,
                           check=True, capture_output=True, text=True)
        if entries:
            # --index-info reads "<mode> <hash>\t<path>"
            info = "".join(f"{meta.split()[0]} {meta.split()[2]}\t{path}\0"
                           for meta, path in entries)
            subprocess.run(git + ["update-index", "-z", "--index-info"],
                           input=info, env=env, check=True,
                           capture_output=True, text=True)
        return subprocess.run(git + ["write-tree"], env=env, check=True,
                              capture_output=True, text=True).stdout.strip()

    try:
        index_tree = tree_with_files(index_commit)
        work_tree = tree_with_files(stash_ref)
    finally:
        try:
            os.unlink(temp_index)
        except OSError:
            pass

    if (index_tree == rev(f"{index_commit}^{{tree}}")
            and work_tree == rev(f"{stash_ref}^{{tree}}")):
        return stash_ref

    def commit_tree(tree: str, parents: list[str], message: str) -> str:
        args = git + ["commit-tree", tree]
        for parent in parents:
            args += ["-p", parent]
        return subprocess.run(args + ["-m", message], check=True,
                              capture_output=True, text=True).stdout.strip()

    new_index = commit_tree(index_tree, [base], "git-cl: index of changelist")
    parents = [base, new_index] + ([untracked_commit] if untracked_commit
                                   else [])
    return commit_tree(work_tree, parents, "git-cl: changes of changelist")


def clutil_apply_stash(
    stash_ref: str,
    base_name: str,
    stash_data: dict
) -> str:
    """
    Restore a stashed changelist, including which changes were staged.

    Applies the changes of the changelist's files from the stash (see
    clutil_stash_for_files()), restores the staged part of these files
    with clutil_restore_index_from_stash() and then drops the stash.

    If applying stops with conflicts, the changes are in the working
    directory with conflict markers, as with 'git stash pop'. The stash
    is kept in case the user needs it again, and the caller restores the
    changelist, because unstashing again would apply the changes twice.
    If the stash cannot be applied at all, nothing changes.

    Args:
        stash_ref: Git stash reference
        base_name: Changelist name for messages
        stash_data: Stash metadata with 'files' and 'file_categories'

    Returns:
        "applied" on success, "conflict" if the changes were applied with
        conflicts, "failed" if nothing was applied.
    """
    git_root = clutil_get_git_root()
    try:
        to_apply = clutil_stash_for_files(stash_ref, stash_data["files"],
                                          git_root)
    except (subprocess.CalledProcessError, OSError):
        # Applying the stash as it is still restores the changelist; only
        # staged changes of other files may come back with it
        to_apply = stash_ref

    try:
        subprocess.run(["git", "stash", "apply", to_apply],
                       capture_output=True, text=True, check=True)
    except subprocess.CalledProcessError as error:
        git_output = f"{error.stdout or ''}\n{error.stderr or ''}"
        if "CONFLICT" in git_output:
            clutil_report_unstash_conflicts(stash_ref, base_name)
            return "conflict"
        clutil_print_error(f"Error: Cannot unstash '{base_name}'. Git reports:")
        for line in (error.stderr or error.stdout or "").strip().splitlines():
            clutil_print_error(f"  {line}")
        clutil_print_error(f"The stash is kept as {stash_ref}.")
        return "failed"

    untracked_files = stash_data.get("file_categories", {}).get("untracked", [])
    try:
        not_restored = clutil_restore_index_from_stash(
            stash_ref, stash_data["files"], untracked_files, git_root)
        if not_restored:
            clutil_print_error("Note: These files changed on this branch since "
                               "they were stashed.")
            clutil_print_error("Their staged changes could not be restored "
                               "and are now unstaged:")
            for path in not_restored:
                clutil_print_error(f"  {path}")
    except subprocess.CalledProcessError:
        clutil_print_error("Warning: Your changes are back, but which of them "
                           "are staged may differ from before.")

    try:
        subprocess.run(["git", "stash", "drop", "--quiet", stash_ref],
                       check=True, capture_output=True, text=True)
    except subprocess.CalledProcessError:
        clutil_print_error(f"Warning: Could not drop {stash_ref}; its changes "
                           "are already restored.")
    return "applied"


def clutil_process_unstash_result(
    base_name: str,
    files: list[str],
    current_branch: Optional[str]
) -> None:
    """
    Process and display results after successful unstash.

    Args:
        base_name: Changelist name
        files: List of files that were restored
        current_branch: Current Git branch
    """
    branch_info = f" to branch '{current_branch}'" if current_branch else ""
    print(f"Unstashed changelist '{base_name}'{branch_info} "
          f"({clutil_plural(len(files), 'file')}):")
    for file_path in files[:10]:
        print(f"  {file_path}")
    if len(files) > 10:
        print(f"  ... and {clutil_plural(len(files) - 10, 'more file')}")


def clutil_update_unstash_metadata(
    base_name: str,
    stash_key: str,
    files: list[str],
    changelists: dict[str, list[str]],
    stashes: dict[str, dict],
    quiet: bool = False
) -> bool:
    """
    Update metadata after successful unstash.

    The stash entry is removed first. If restoring the changelist fails
    afterwards, the files are back in the working directory and only the
    changelist has to be recreated, which the warning explains.

    Args:
        base_name: Changelist name
        stash_key: Key in stashes dictionary
        files: List of files in the changelist
        changelists: Active changelists dictionary (will be modified)
        stashes: Stashed changelists dictionary (will be modified)
        quiet: If True, suppress verbose output

    Returns:
        True if the metadata was updated, False otherwise.
    """
    try:
        del stashes[stash_key]
        clutil_save_stashes(stashes)

        changelists[base_name] = files.copy()
        clutil_save(changelists)

    except (OSError, subprocess.CalledProcessError,
            json.JSONDecodeError) as metadata_error:
        clutil_print_error(f"Warning: Unstash succeeded but metadata update failed: "
                           f"{metadata_error}")
        clutil_print_error(f"Manually recreate the changelist: git cl add "
                           f"{base_name} <files>")
        return False

    if not quiet:
        current_branch = clutil_get_current_branch()
        clutil_process_unstash_result(base_name, files, current_branch)
    return True


def clutil_prepare_stash_files(
    files: list[str],
    git_root: Path
) -> tuple[list[tuple[str, Path]], list[str]]:
    """
    Prepare files for stashing by checking existence.

    Args:
        files: List of file paths from changelist
        git_root: Git repository root

    Returns:
        Tuple of (existing_files, missing_files)
    """
    missing_files = []
    existing_files = []

    for stored_path in files:
        abs_path = clutil_resolve_file(git_root / stored_path)
        if not clutil_path_exists(abs_path):
            missing_files.append(stored_path)
        else:
            existing_files.append((stored_path, abs_path))

    return existing_files, missing_files


def clutil_print_stash_success(
    name: str,
    stashable_files: list[str],
    current_branch: Optional[str]
) -> None:
    """
    Print success message after stashing.

    Args:
        name: Changelist name
        stashable_files: List of files that were stashed
        current_branch: Current Git branch
    """
    branch_info = f" from branch '{current_branch}'" if current_branch else ""
    print(f"Stashed changelist '{name}'{branch_info} "
          f"({clutil_plural(len(stashable_files), 'file')}):")
    for file_path in stashable_files[:10]:
        print(f"  {file_path}")
    if len(stashable_files) > 10:
        print(f"  ... and {clutil_plural(len(stashable_files) - 10, 'more file')}")


def clutil_show_active_changelists(
    changelists: dict[str, list[str]],
    selected_names: Optional[set[str]],
    status_map: dict[str, str],
    git_root: Path,
    use_color: bool
) -> tuple[bool, set[str]]:
    """
    Display active changelists and return assigned files.

    Args:
        changelists: Active changelists
        selected_names: Set of names to filter by (None = show all)
        status_map: Git status mapping
        git_root: Git repository root
        use_color: Whether to use coloured output

    Returns:
        Tuple of (shown_any, assigned_files)
    """
    assigned_files = set()
    shown_any = False

    for cl_name, files in changelists.items():
        for f in files:
            try:
                abs_path = clutil_resolve_file(git_root / f)
                assigned_files.add(abs_path.relative_to(git_root).as_posix())
            except (ValueError, OSError) as error:
                clutil_print_error(f"Error resolving path: {error}")

        if selected_names is not None and cl_name not in selected_names:
            continue

        if files:
            print(f"{cl_name}:")
            shown_any = True
            for file in files:
                clutil_print_status_line(
                    clutil_format_file_status(file, status_map, git_root,
                                              use_color))

    return shown_any, assigned_files


def clutil_show_stashed_changelists(stashes: dict[str, dict]) -> None:
    """
    Display stashed changelists section.

    Args:
        stashes: Dictionary of stashed changelists
    """
    print("Stashed Changelists:")

    # Sort by timestamp (most recent first)
    stashed_items = []
    for stash_name, stash_data in stashes.items():
        timestamp = stash_data.get('timestamp', '')
        file_count = len(stash_data.get('files', []))
        stashed_items.append((stash_name, file_count, timestamp))

    # Sort by timestamp descending (most recent first)
    stashed_items.sort(key=lambda x: x[2], reverse=True)

    for stash_name, file_count, timestamp in stashed_items:
        # Format timestamp for display
        try:
            dt = datetime.datetime.fromisoformat(timestamp)
            formatted_time = dt.strftime("%Y-%m-%d %H:%M")
        except (ValueError, AttributeError):
            formatted_time = "unknown time"

        file_word = "file" if file_count == 1 else "files"
        print(f"  {stash_name} ({file_count} {file_word}, {formatted_time})")


def clutil_validate_unstash_environment(
    base_name: str,
    stash_key: str,
    stashes: dict[str, dict],
    changelists: dict[str, list[str]],
    force: bool,
    ignore_untracked: bool = False
) -> tuple[Optional[str], Optional[dict]]:
    """
    Validate all preconditions for unstashing.

    Args:
        base_name: Base changelist name
        stash_key: Key in stashes dictionary
        stashes: Stashed changelists
        changelists: Active changelists
        force: Whether to force despite warnings
        ignore_untracked: Whether untracked files are allowed in the
            clean working directory check

    Returns:
        Tuple of (error_message, stash_data) - error_message is None if valid
    """
    # Validate basic preconditions
    error_msg = clutil_validate_unstash_preconditions(
        base_name, stash_key, stashes, changelists
    )
    if error_msg:
        return error_msg, None

    stash_data = stashes[stash_key]
    source_branch = clutil_get_stash_source_branch(stash_data)

    # Check branch workflow requirements
    error_msg = clutil_check_branch_workflow(base_name, source_branch, force,
                                             ignore_untracked)
    if error_msg:
        return error_msg, None

    return None, stash_data


# =============================================================================
# BRANCH WORKFLOW UTILITIES (branch-specific utilities)
# =============================================================================

def clutil_validate_branch_preconditions(
        changelist_name: str, changelists: dict, stashes: dict) -> str:
    """Validate preconditions for branch creation workflow."""
    if changelist_name in stashes and changelist_name not in changelists:
        return (f"Error: Changelist '{changelist_name}' is stashed.\n"
                f"Unstash it first with 'git cl unstash {changelist_name}', "
                "then run git cl branch again.")

    if changelist_name not in changelists:
        error_msg = f"Error: Changelist '{changelist_name}' not found."
        available = [name for name in changelists.keys() if changelists[name]]
        if available:
            error_msg += "\nAvailable active changelists:"
            for name in available:
                error_msg += f"\n  {name}"
        return error_msg

    if not changelists[changelist_name]:
        return (f"Error: Changelist '{changelist_name}' is empty.\n"
                f"Add files with: git cl add {changelist_name} <files>")

    if changelist_name in stashes:
        return (f"Error: Changelist '{changelist_name}' is already stashed.\n"
                f"Use 'git cl unstash {changelist_name}' to restore it first.")

    return ""


def clutil_check_branch_exists(branch_name: str) -> bool:
    """Check if a branch already exists."""
    try:
        result = subprocess.run(["git", "show-ref", "--verify",
                                 f"refs/heads/{branch_name}"],
                                capture_output=True, text=True, check=False)
        return result.returncode == 0
    except subprocess.CalledProcessError:
        return False


def clutil_get_submodule_paths(git_root: Path) -> list[str]:
    """
    Return the paths of all submodules, relative to the Git root.

    A submodule is recorded in the index as a 'gitlink' (mode 160000): a
    pointer to a commit of another repository, not a file. Changelists
    contain files only, so submodules are kept out of them, just like
    directories.

    Args:
        git_root: Path to the Git repository root

    Returns:
        Submodule paths, e.g. ["libs/sub"]. Empty if there are none or
        Git fails.
    """
    try:
        output = subprocess.run(
            ["git", "-C", str(git_root), "ls-files", "--stage", "-z"],
            check=True, capture_output=True, text=True).stdout
    except subprocess.CalledProcessError:
        return []
    paths = []
    for entry in output.split("\0"):
        info, _, path = entry.partition("\t")
        if path and info.startswith("160000 "):
            paths.append(path)
    return paths


def clutil_find_submodule(path: str, submodules: list[str]) -> Optional[str]:
    """
    Return the submodule that is or contains a path, if any.

    Args:
        path: Path relative to the Git root
        submodules: Paths from clutil_get_submodule_paths()

    Returns:
        The submodule path, or None if the path is not in a submodule.
    """
    for submodule in submodules:
        if path == submodule or path.startswith(submodule + "/"):
            return submodule
    return None


def clutil_get_changed_submodule_pointers(
    git_root: Path,
    submodules: list[str]
) -> set[str]:
    """
    Return the submodules whose recorded commit differs from HEAD.

    Changes inside a submodule that are not committed there belong to the
    submodule's own repository and are ignored ('--ignore-submodules=
    dirty'). A new commit in the submodule changes the pointer in this
    repository, which is a change here.

    Args:
        git_root: Path to the Git repository root
        submodules: Paths from clutil_get_submodule_paths()

    Returns:
        Submodule paths whose pointer changed in the index or working
        directory. If Git fails, all submodules are returned, so that no
        change is overlooked.
    """
    if not submodules:
        return set()
    try:
        output = subprocess.run(
            ["git", "-C", str(git_root), "diff", "HEAD", "--name-only", "-z",
             "--ignore-submodules=dirty", "--"]
            + clutil_literal_pathspecs(submodules),
            check=True, capture_output=True, text=True).stdout
    except subprocess.CalledProcessError:
        return set(submodules)
    return {path for path in output.split("\0") if path}


def clutil_check_unassigned_changes(changelists: dict,
                                    git_root: Path) -> list[str]:
    """
    Check for uncommitted changes not in any changelist.

    Untracked files are ignored, and so are submodules with uncommitted
    changes of their own. A submodule whose recorded commit changed is
    reported, because the change would move to a new branch unnoticed.
    """
    status_map = clutil_get_file_status_map()

    # Get all files assigned to changelists
    assigned_files = set()
    for files in changelists.values():
        for file_path in files:
            try:
                abs_path = clutil_resolve_file(git_root / file_path)
                rel_path = abs_path.relative_to(git_root).as_posix()
                assigned_files.add(rel_path)
            except (ValueError, OSError):
                continue

    # Submodules whose own files changed, but whose recorded commit did
    # not, have no change in this repository
    submodules = clutil_get_submodule_paths(git_root)
    changed_pointers = clutil_get_changed_submodule_pointers(git_root,
                                                             submodules)

    # Check for unassigned changes (ignore untracked files)
    return [file_path for file_path, status in status_map.items()
            if file_path not in assigned_files and status != "??"
            and (file_path not in submodules or file_path in changed_pointers)]


def clutil_validate_changelists_stashable(
        changelists: dict[str, list[str]],
        git_root: Path,
        status_map: dict[str, str]) -> dict[str, list[tuple[str, str]]]:
    """
    Pre-flight check that every changelist contains only stashable files.

    'git cl br' must stash ALL active changelists before creating the
    branch. cl_stash deliberately refuses a changelist that contains
    clean files, staged-only modifications, or no stashable changes at
    all. Without this check, such a changelist would abort the workflow
    halfway through: some changelists stashed, others not, and the new
    branch created on top of a dirty working directory (issue #51).
    This function reports all problems up front, before any state is
    mutated, so the user can clean up first.

    Additionally, when more than one changelist is stashed, no file may
    have a staged component (e.g. 'A ' staged additions): git builds a
    pathspec-limited stash from the FULL index, so any staged file —
    even one belonging to another changelist — leaks into every stash
    created while it is staged, and reappears when that stash is
    applied. Staged files must be removed from the index first, e.g.
    with 'git cl unstage <changelist>' (issue #51).

    Args:
        changelists: Active (non-empty) changelists to validate
        git_root: Git repository root
        status_map: Precomputed status map from
                    clutil_get_file_status_map()

    Returns:
        Mapping of changelist name to a list of (stored path, kind) pairs,
        where kind is 'clean', 'staged-only', 'staged', 'other', or
        'empty' (with an empty path). An empty dict means every changelist
        is fully stashable and the branch workflow may proceed.
    """
    problems: dict[str, list[tuple[str, str]]] = {}

    active = {name: files for name, files in changelists.items() if files}
    multiple_changelists = len(active) > 1

    for name, files in sorted(active.items()):
        existing_files, missing_files = clutil_prepare_stash_files(
            files, git_root)
        file_categories, stashable_files, unstashable_files = (
            clutil_categorize_files_for_stash(
                existing_files, missing_files, status_map, git_root))

        messages = []
        for file_path in file_categories['clean_files']:
            messages.append((file_path, "clean"))
        for file_path in file_categories['staged_modifications']:
            messages.append((file_path, "staged-only"))
        known_unstashable = (set(file_categories['clean_files'])
                             | set(file_categories['staged_modifications']))
        for file_path in unstashable_files:
            if file_path not in known_unstashable:
                messages.append((file_path, "other"))
        if not unstashable_files and not stashable_files:
            messages.append(("", "empty"))

        # Staged components leak into every pathspec stash created while
        # they sit in the index (git records the full index state). With
        # a single changelist there is nothing to leak into; with several
        # the file would silently reappear when another stash is applied.
        if multiple_changelists:
            for stored_path, abs_path in existing_files:
                rel = abs_path.relative_to(git_root).as_posix()
                status = status_map.get(rel, "  ")
                if (status[0] not in (' ', '?')
                        and stored_path not in known_unstashable):
                    messages.append((stored_path, "staged"))

        if messages:
            problems[name] = messages

    return problems


def clutil_report_branch_problems(
        problems: dict[str, list[tuple[str, str]]],
        status_map: dict[str, str], git_root: Path,
        args: argparse.Namespace) -> None:
    """Explain why 'git cl br' cannot stash every changelist, and what to do."""
    reasons = {"clean": "no changes", "staged-only": "only staged changes",
               "staged": "staged", "other": "not stashable"}
    cwd = Path.cwd().resolve()
    clutil_print_error("Error: Cannot create the branch: git cl br stashes every "
                       "active changelist\nfirst, and these files cannot be "
                       "stashed:")
    for cl_name, entries in sorted(problems.items()):
        clutil_print_error(f"  {cl_name}:")
        for path, kind in entries:
            if kind == "empty":
                clutil_print_error("    (no changes to stash)")
                continue
            clutil_print_error(f"    [{status_map.get(path, '  ')}] "
                               f"{_relpath(git_root / path, cwd)} "
                               f"({reasons[kind]})")
    to_unstage = sorted(name for name, entries in problems.items()
                        if any(k in ("staged", "staged-only") for _, k in entries))
    clean = [path for entries in problems.values()
             for path, kind in entries if kind == "clean"]
    if to_unstage:
        clutil_print_error(f"Unstage them: git cl unstage {' '.join(to_unstage)}")
    if clean:
        clutil_print_error("Remove files without changes: git cl rm "
                           f"{clutil_shell_paths(clean, git_root)}")
    retry = ["git cl br", args.changelist_name]
    if getattr(args, 'branch_name', None):
        retry.append(args.branch_name)
    if getattr(args, 'from_branch', None):
        retry.append(f"--from {args.from_branch}")
    clutil_print_error(f"Then run: {' '.join(retry)}")


def clutil_create_branch(branch_name: str,
                         base_branch: str, current_branch: str) -> None:
    """Create new branch from base."""
    if base_branch != current_branch:
        # Create branch from specified base
        subprocess.run(["git", "checkout", "-b", branch_name, base_branch],
                       check=True)
    else:
        # Create branch from current HEAD
        subprocess.run(["git", "checkout", "-b", branch_name], check=True)


def clutil_unstash_changelist(changelist_name: str) -> bool:
    """
    Unstash specific changelist for 'git cl br'. Returns True on success.

    Untracked files outside any changelist are not stashed by 'git cl br',
    so they are still present after the switch to the new branch. They
    must not count as an unclean working directory here, matching the
    pre-flight check in clutil_check_unassigned_changes(). Conflict checks
    stay in force.
    """
    temp_unstash_args = argparse.Namespace()
    temp_unstash_args.name = changelist_name
    temp_unstash_args.force = False
    temp_unstash_args.all = False
    temp_unstash_args.ignore_untracked = True
    return cl_unstash(temp_unstash_args, quiet=True)


def clutil_handle_branch_creation_failure() -> None:
    """Handle failure during branch creation by restoring stashes."""
    try:
        temp_unstash_args = argparse.Namespace()
        temp_unstash_args.all = True
        temp_unstash_args.force = True
        cl_unstash(temp_unstash_args)
    except (OSError, subprocess.CalledProcessError,
            json.JSONDecodeError) as restore_error:
        clutil_report_failure("Could not restore the stashed changelists",
                              restore_error)
        clutil_print_error("You may need to manually unstash: git cl unstash --all")


# =============================================================================
# CLI COMMANDS
# =============================================================================

# Every cl_* command returns True on success and False on failure; main()
# turns this into exit code 0 or 1. A command that finds nothing to do
# (e.g. no tracked files to stage) has succeeded. A command that handles
# several names or paths still processes the valid ones, but returns False
# if any of them was rejected. Errors, warnings and their hints are
# printed on stderr via clutil_print_error(), regular output on stdout.

# Up to this many changed files under a directory are listed in a hint;
# beyond that only their number is shown, to keep the output short.
MAX_DIRECTORY_HINT_FILES = 10


# pylint: disable-next=too-many-arguments
def clutil_report_submodule_path(
    file: str,
    sanitized: str,
    submodule: str,
    name: str,
    git_root: Path,
    cwd: Path
) -> None:
    """
    Explain why a submodule, or a path inside one, cannot be added.

    A submodule is a separate repository. Its files are grouped with
    git cl inside the submodule; its recorded commit is committed with
    plain git, like a directory is never part of a changelist.

    Args:
        file: The path as the user gave it
        sanitized: The path relative to the Git root
        submodule: The submodule path relative to the Git root
        name: The changelist name the user asked for
        git_root: Path to the Git repository root
        cwd: The current working directory
    """
    submodule_display = shlex.quote(_relpath(git_root / submodule, cwd))
    if sanitized == submodule:
        clutil_print_error(f"Error: '{file}' is a submodule. Changelists "
                           "contain files only.")
        clutil_print_error("To group files inside it, run git cl in the "
                           "submodule:")
        clutil_print_error(f"  cd {submodule_display} && git cl add {name} "
                           "<files>")
        clutil_print_error("To record its new commit: git add "
                           f"{submodule_display}")
    else:
        inside = shlex.quote(sanitized[len(submodule) + 1:])
        clutil_print_error(f"Error: '{file}' is inside the submodule "
                           f"'{submodule}', which is a separate repository.")
        clutil_print_error("Run git cl there:")
        clutil_print_error(f"  cd {submodule_display} && git cl add {name} "
                           f"{inside}")


def clutil_directory_hint(
        dir_path: str, name: str, status_map: dict[str, str],
        git_root: Path) -> list[str]:
    """
    Build the lines that list the changed files under a directory and the
    'git cl add' command to add them to a changelist.

    Changelists contain files only. When a directory is given, this hint
    shows which files it would mean, so the user can add them by name.
    Every file with a Git status is listed the same way, including
    untracked files, with its status code in front.

    Args:
        dir_path: Directory path relative to the git root
        name: Changelist name for the suggested command
        status_map: Status map including untracked files
        git_root: Repository root

    Returns:
        The hint lines, without the error line itself.
    """
    prefix = dir_path.rstrip("/") + "/"
    if dir_path in ("", "."):
        prefix = ""
    changed = sorted(path for path in status_map if path.startswith(prefix))
    display = _relpath(clutil_resolve_file(git_root / dir_path),
                       Path.cwd().resolve())

    if not changed:
        return [f"No changed files under '{display}'."]

    if len(changed) > MAX_DIRECTORY_HINT_FILES:
        return [f"{len(changed)} changed files under '{display}'. Run "
                "'git cl status' to see them, then add the files you want "
                "by name."]

    cwd = Path.cwd().resolve()
    lines = [f"Changed files under '{display}':"]
    lines += [clutil_format_file_status(path, status_map, git_root, False)
              for path in changed]
    paths = " ".join(shlex.quote(_relpath(clutil_resolve_file(git_root / path), cwd))
                     for path in changed)
    lines.append("To add them, run:")
    lines.append(f"  git cl add {name} {paths}")
    return lines


def cl_add(args: argparse.Namespace) -> bool:
    """
    Adds one or more files to the specified changelist, creating it if needed.
    Prevents adding files that are in stashed changelists.

    Changelists contain files only. A directory is rejected with a hint
    that lists the changed files under it; the other paths are still
    added, and the command exits with 1.
    """
    if not clutil_validate_name(args.name):
        clutil_print_error(
            f"Error: Invalid changelist name '{args.name}'.\n"
            "Use letters, digits, '-', '_' and '.' (at most 100 characters), "
            "for example 'my-feature'.\nNames made only of dots and Git "
            "names such as HEAD are not allowed.")
        return False

    changelists = clutil_load()
    stashes = clutil_load_stashes()
    git_root = clutil_get_git_root()

    # An active changelist with the name of a stashed one would block
    # 'git cl unstash', which refuses to overwrite an existing changelist.
    if args.name in stashes:
        clutil_print_error(f"Error: Changelist '{args.name}' is stashed.")
        if clutil_find_orphaned_stashes({args.name: stashes[args.name]}):
            clutil_print_orphaned_stash_hint(args.name)
        else:
            clutil_print_error(f"Unstash it first with 'git cl unstash "
                               f"{args.name}', or choose another name.")
        return False

    status_map = clutil_get_file_status_map(
                                            include_untracked=True)

    submodules = clutil_get_submodule_paths(git_root)
    cwd = Path.cwd().resolve()

    known = (clutil_known_paths(git_root, status_map, changelists)
             if clutil_ignores_case() else None)

    files = []
    skipped = False
    for file in args.files:
        sanitized = clutil_sanitize_path(file, git_root)
        if sanitized and known is not None:
            sanitized = clutil_match_case(sanitized, known, git_root)
        if sanitized:
            abs_path = clutil_resolve_file(git_root / sanitized)
            submodule = clutil_find_submodule(sanitized, submodules)
            if submodule:
                clutil_report_submodule_path(file, sanitized, submodule,
                                             args.name, git_root, cwd)
                skipped = True
                continue
            if clutil_is_real_dir(abs_path):
                clutil_print_error(f"Error: '{file}' is a directory. "
                                   "Changelists contain files only.")
                for line in clutil_directory_hint(sanitized, args.name,
                                                  status_map, git_root):
                    clutil_print_error(line)
                skipped = True
                continue
            # A trailing slash on a symlink to a directory means its
            # contents, not the symlink. Git rejects such a path as
            # 'beyond a symbolic link', so point to both options.
            if (file.endswith(("/", os.sep)) and abs_path.is_symlink()
                    and abs_path.is_dir()):
                link_display = file.rstrip("/" + os.sep)
                clutil_print_error(f"Error: '{file}' is a symlink to a "
                                   "directory. Changelists contain files "
                                   "only.")
                clutil_print_error("To add the symlink itself, use "
                                   f"'{link_display}'.")
                try:
                    target = abs_path.resolve().relative_to(git_root)
                except ValueError:
                    clutil_print_error("Its target is outside the "
                                       "repository.")
                else:
                    for line in clutil_directory_hint(
                            target.as_posix(), args.name, status_map,
                            git_root):
                        clutil_print_error(line)
                skipped = True
                continue
            # Warn if the file is neither on disk nor known to Git. A deleted
            # tracked file has a Git status and is a valid change to add.
            if not clutil_path_exists(abs_path) and sanitized not in status_map:
                clutil_print_error(f"Warning: File '{file}' does not exist.")
            files.append(sanitized)
        else:
            clutil_print_error(f"Error: Skipping invalid or unsafe path: '{file}'")
            skipped = True

    # Check if any files are in stashed changelists
    blocked_files = []
    for file_path in files:
        for stash_name, stash_data in stashes.items():
            if file_path in stash_data['files']:
                blocked_files.append((file_path, stash_name))

    if blocked_files:
        clutil_print_error("Error: Cannot add files that are in stashed changelists:")
        for file_path, stash_name in blocked_files:
            clutil_print_error(f"  {file_path} (in stashed changelist '{stash_name}')")
        blocking = {name: stashes[name] for _, name in blocked_files}
        orphaned = clutil_find_orphaned_stashes(blocking)
        if orphaned:
            for name in orphaned:
                clutil_print_orphaned_stash_hint(name)
        else:
            clutil_print_error("Unstash the changelist first if you want to "
                               "modify it.")
        return False

    if args.name not in changelists:
        changelists[args.name] = []

    moved: dict[str, list[str]] = {}
    for file in files:
        # Remove from other active changelists
        for other, clist in changelists.items():
            if file in clist and other != args.name:
                clist.remove(file)
                moved.setdefault(other, []).append(file)
        if file not in changelists[args.name]:
            changelists[args.name].append(file)

    clutil_save(changelists)
    if files:
        print(f"Added to '{args.name}': {clutil_shell_paths(files, git_root)}")
    for other, paths in sorted(moved.items()):
        print(f"  moved from '{other}': {clutil_shell_paths(paths, git_root)}")
    return not skipped


def cl_stage(args: argparse.Namespace) -> bool:
    """
    Stages all tracked files in one or more changelists and optionally
    deletes them.

    If any named changelist does not exist, nothing is staged.

    Args:
        args: argparse.Namespace with 'names' and 'delete' attributes.
    """
    changelists = clutil_load()
    names = clutil_resolve_changelist_names(args.names, changelists,
                                            "staged")
    if names is None:
        return False

    git_root = clutil_get_git_root()

    # Fetch git status once and reuse for all files in the changelists
    status_map = clutil_get_file_status_map()

    if clutil_refuse_on_merge_conflict(status_map, "stage"):
        return False

    to_stage, files_by_name = clutil_collect_changelist_files(
        names, changelists, git_root, status_map,
        lambda path: path in status_map
        and not clutil_is_file_untracked_cached(path, status_map))

    label = clutil_changelist_label(names)
    if not to_stage:
        print(f"No tracked files with changes to stage in {label}.")
        clutil_hint_untracked(names, changelists, status_map)
        return True

    # A staged deletion ('D ') is already fully staged and no longer exists
    # in the index or on disk, so 'git add' would reject the path
    cwd = Path.cwd().resolve()
    to_add = [
        file for file in to_stage
        if status_map.get(
            clutil_resolve_file(cwd / file).relative_to(git_root).as_posix()) != "D "
    ]

    try:
        if to_add:
            subprocess.run(["git", "add", "--"]
                           + clutil_literal_pathspecs(to_add), check=True)
    except subprocess.CalledProcessError as error:
        clutil_report_failure(f"Could not stage {label}", error)
        return False

    clutil_print_files_by_changelist("Staged tracked files from", names,
                                     to_stage, files_by_name)

    # Only delete if --delete flag is set
    if args.delete:
        for name in names:
            del changelists[name]
        clutil_save(changelists)
        print(f"Deleted {label}")
    return True


def cl_unstage(args: argparse.Namespace) -> bool:
    """
    Unstages all staged files in one or more changelists, moving them back
    to the working directory as unstaged changes.

    If any named changelist does not exist, nothing is unstaged.

    Args:
        args: argparse.Namespace with 'names' and 'delete' attributes.
    """
    changelists = clutil_load()
    names = clutil_resolve_changelist_names(args.names, changelists,
                                            "unstaged")
    if names is None:
        return False

    git_root = clutil_get_git_root()

    # Get current status to identify staged files
    status_map = clutil_get_file_status_map()

    if clutil_refuse_on_merge_conflict(status_map, "unstage"):
        return False

    # A file has staged changes if the first status character is not a
    # space; untracked files ('??') have nothing staged
    to_unstage, files_by_name = clutil_collect_changelist_files(
        names, changelists, git_root, status_map,
        lambda path: status_map.get(path, "  ")[0] not in " ?")

    label = clutil_changelist_label(names)
    if not to_unstage:
        print(f"No staged files to unstage in {label}.")
        return True

    try:
        # Use git reset HEAD to unstage files
        subprocess.run(["git", "reset", "--quiet", "HEAD", "--"]
                       + clutil_literal_pathspecs(to_unstage),
                       check=True)
    except subprocess.CalledProcessError as error:
        clutil_report_failure(f"Could not unstage {label}", error)
        return False

    clutil_print_files_by_changelist("Unstaged files from", names,
                                     to_unstage, files_by_name)

    # Only delete if --delete flag is set
    if args.delete:
        for name in names:
            del changelists[name]
        clutil_save(changelists)
        print(f"Deleted {label}")
    return True


def cl_status(args: argparse.Namespace) -> bool:
    """
    Displays git status grouped by changelist membership,
    including stashed changelists.

    Shows active changelists first, then a separate "Stashed Changelists" section,
    then unassigned files. Filtering by changelist names applies only to active
    changelists unless --include-no-cl is specified.
    """
    selected_names = set(args.names) if args.names else None
    changelists = clutil_load()
    stashes = clutil_load_stashes()
    git_root = clutil_get_git_root()
    status_map = clutil_get_file_status_map(
        include_untracked=not args.no_untracked)

    use_color = clutil_should_use_color(args)

    for name in sorted(selected_names or []):
        if name not in changelists:
            clutil_print_error(f"Warning: No active changelist '{name}'.")

    if (selected_names is None and not changelists and not stashes
            and not status_map and not args.no_untracked):
        print("No changelists and no changes.")
        return True

    # Show active changelists
    shown_any_active, assigned_files = clutil_show_active_changelists(
        changelists, selected_names, status_map, git_root, use_color
    )

    # Show stashed changelists section
    if stashes and (selected_names is None):  # Only show when not filtering
        if shown_any_active:
            print()  # Add spacing
        clutil_show_stashed_changelists(stashes)

    # Show unassigned files
    if selected_names is None or args.include_no_cl:
        no_cl_files = [file for file in status_map if file not in assigned_files]
        if no_cl_files:
            if shown_any_active or stashes:
                print()  # Add spacing
            print("No Changelist:")
            for file in sorted(no_cl_files):
                clutil_print_status_line(
                    clutil_format_file_status(file, status_map, git_root,
                                              use_color))

    # Advise user about directory entries, which older versions accepted.
    # Changelists contain files only; the entry is left in place.
    dir_notes = []
    full_status_map = None
    cwd = Path.cwd().resolve()
    for name, files in changelists.items():
        if selected_names is not None and name not in selected_names:
            continue
        for entry in files:
            if not clutil_is_real_dir(git_root / entry):
                continue
            if full_status_map is None:
                full_status_map = clutil_get_file_status_map(
                    include_untracked=True)
            display = _relpath(clutil_resolve_file(git_root / entry), cwd)
            dir_notes.append(f"Note: '{display}' in changelist '{name}' is "
                             "a directory. Changelists contain files only.")
            dir_notes.append("      Remove it with 'git cl rm "
                             f"{shlex.quote(display)}', then add the files "
                             "you want by name.")
            dir_notes += ["      " + line for line in clutil_directory_hint(
                entry, name, full_status_map, git_root)]
    if dir_notes:
        print()
        print("\n".join(dir_notes))

    # Advise user if a rename is split across changelists
    renames = clutil_get_renames()
    if renames:
        notes = []
        for name in changelists:
            if selected_names is None or name in selected_names:
                notes += clutil_note_split_renames([name], changelists,
                                                   renames, git_root)
        if notes:
            print()
            print("\n".join(notes))

    # Advise user if conflicts are present
    conflicts = clutil_detect_merge_conflicts(status_map)
    if conflicts:
        print()
        print(f"Note: {clutil_plural(len(conflicts), 'file')} with merge "
              "conflicts. "
              "Resolve before staging, committing, or stashing.")
    return True


def cl_diff(args: argparse.Namespace) -> bool:
    """
    Show git diff for one or more changelists.

    By default, shows unstaged changes (like `git diff`).
    Use --staged for staged changes, or --both to show both.

    Args:
        args: argparse.Namespace with 'names' list of changelists,
              and optional 'staged' and 'both' flags
    """
    changelists = clutil_load()
    git_root = clutil_get_git_root()
    diff_files = set()
    missing_changelist = False

    # A deleted file is gone from the working directory, but Git still
    # knows it from the index or HEAD and shows the deletion
    all_paths = [path for name in args.names
                 for path in changelists.get(name, [])]
    known_to_git = (clutil_get_paths_in_index(git_root, all_paths)
                    | clutil_get_paths_in_head(git_root, all_paths))
    cwd = Path.cwd().resolve()

    for name in args.names:
        if name not in changelists:
            clutil_print_error(f"Error: Changelist '{name}' not found.")
            missing_changelist = True
            continue
        for path in changelists[name]:
            abs_path = clutil_resolve_file(git_root / path)
            if clutil_path_exists(abs_path) or path in known_to_git:
                diff_files.add(_relpath(abs_path, cwd))
            else:
                clutil_print_error(f"Warning: File '{path}' from '{name}' does not "
                                   "exist.")

    if not diff_files:
        if missing_changelist:
            return False
        print("No valid files to diff.")
        return True

    sorted_files = sorted(diff_files)

    def run_diff(extra: list[str]) -> bool:
        """Run one git diff; report a failure and return False on it."""
        sys.stdout.flush()
        try:
            result = subprocess.run(["git", "diff"] + extra + ["--"]
                                    + clutil_literal_pathspecs(sorted_files), check=False)
        except OSError as error:
            clutil_print_error(f"Error running git diff: {error}")
            return False
        if result.returncode != 0:
            clutil_print_error(f"Error: git diff {' '.join(extra)}".rstrip()
                               + f" failed with exit code {result.returncode}.")
            return False
        return True

    if args.both:
        # Show both unstaged and staged diffs; a failure of one does not
        # stop the other
        print("=== Unstaged changes (working tree vs index) ===")
        unstaged_ok = run_diff([])
        print("\n=== Staged changes (index vs HEAD) ===")
        staged_ok = run_diff(["--staged"])
        succeeded = unstaged_ok and staged_ok
    elif args.staged:
        succeeded = run_diff(["--staged"])
    else:
        succeeded = run_diff([])

    return succeeded and not missing_changelist


def clutil_get_paths_in_index(git_root: Path, paths: list[str]) -> set[str]:
    """
    Return which of the given paths are in the index.

    Args:
        git_root: Path to the Git repository root
        paths: File paths relative to the Git root

    Returns:
        The subset of paths that are in the index. Empty if Git fails.
    """
    if not paths:
        return set()
    try:
        output = subprocess.run(
            ["git", "-C", str(git_root), "ls-files", "-z", "--cached", "--"]
            + clutil_literal_pathspecs(paths),
            check=True, capture_output=True, text=True).stdout
    except subprocess.CalledProcessError:
        return set()
    return {path for path in output.split("\0") if path}


def clutil_get_paths_in_head(git_root: Path, paths: list[str]) -> set[str]:
    """
    Return which of the given paths exist as files in HEAD.

    Args:
        git_root: Path to the Git repository root
        paths: File paths relative to the Git root

    Returns:
        The subset of paths that are in HEAD. Empty if there is no commit
        yet or Git fails.
    """
    if not paths:
        return set()
    try:
        output = subprocess.run(
            ["git", "-C", str(git_root), "ls-tree", "-r", "-z", "--name-only",
             "HEAD", "--"] + clutil_literal_pathspecs(paths),
            check=True, capture_output=True, text=True).stdout
    except subprocess.CalledProcessError:
        return set()
    return {path for path in output.split("\0") if path}


def cl_checkout(args: argparse.Namespace) -> bool:
    """
    Checkout (revert) files from one or more changelists to their HEAD state.

    This discards local changes in the working directory for the specified files,
    reverting them to their last committed state. Useful for undoing unwanted
    local modifications. Optionally deletes the changelist(s) after checkout.

    Args:
        args: argparse.Namespace with 'names' list of changelist names,
              optional 'force' flag for confirmation, and optional 'delete'
              flag to remove changelist(s) after checkout.
    """
    # A name given twice is handled once, as in stage and commit
    args.names = list(dict.fromkeys(args.names))
    changelists = clutil_load()
    git_root = clutil_get_git_root()

    # Check for merge conflicts before doing anything destructive
    status_map = clutil_get_file_status_map()
    if clutil_refuse_on_merge_conflict(status_map, "checkout"):
        return False

    # Collect all files from specified changelists
    all_files = []
    missing_changelists = []

    for name in args.names:
        if name not in changelists:
            missing_changelists.append(name)
            continue

        files = changelists[name]
        if not files:
            clutil_print_error(f"Warning: Changelist '{name}' is empty.")
            continue

        all_files.extend(files)

    # Report missing changelists
    if missing_changelists:
        clutil_print_error("Error: The following changelists were not found:")
        for name in missing_changelists:
            clutil_print_error(f"  {name}")
        if not all_files:  # No valid changelists found
            return False

    if not all_files:
        print("No files to checkout.")
        return True

    # Only files in HEAD can be reverted to it. This includes deleted
    # files, which are restored. git checkout would reject the whole
    # pathspec for a single file that is not in HEAD, so such files are
    # filtered out and reported separately.
    in_head = clutil_get_paths_in_head(git_root, all_files)

    # Convert to paths relative to current working directory for git command
    checkout_files = []
    missing_files = []
    untracked_files = []
    new_files = []

    for stored_path in all_files:
        abs_path = clutil_resolve_file(git_root / stored_path)

        if stored_path in in_head:
            # Files without changes have nothing to revert
            if stored_path in status_map:
                checkout_files.append(_relpath(abs_path, Path.cwd().resolve()))
        elif clutil_is_file_untracked_cached(stored_path, status_map):
            untracked_files.append(stored_path)
        elif clutil_path_exists(abs_path):
            # Staged as a new file (or as the new name of a rename)
            new_files.append(stored_path)
        else:
            missing_files.append(stored_path)

    # Report missing files
    if missing_files:
        clutil_print_error("Warning: The following files do not exist and will be "
                           "skipped:")
        for file_path in missing_files:
            clutil_print_error(f"  {file_path}")

    # Report untracked files (cannot be reverted - no committed state)
    if untracked_files:
        clutil_print_error("Warning: The following untracked files cannot be reverted "
                           "and will be skipped:")
        for file_path in untracked_files:
            clutil_print_error(f"  {file_path}")

    # Report new files (not in HEAD, so there is nothing to revert to)
    if new_files:
        clutil_print_error("Warning: The following new files are not in HEAD "
                           "and will be skipped:")
        for file_path in new_files:
            clutil_print_error(f"  {file_path}")
        clutil_print_error("To unstage them and keep the files: git restore "
                           f"--staged -- {clutil_shell_paths(new_files, git_root)}")

    if not checkout_files:
        print("No files with changes to revert to HEAD.")
        return not missing_changelists

    # Show what will be affected and ask for confirmation unless --force
    print("This will discard local changes in "
          f"{clutil_plural(len(checkout_files), 'file')}:")
    for file_path in checkout_files[:10]:  # Show first 10 files
        print(f"  {file_path}")
    if len(checkout_files) > 10:
        print(f"  ... and {clutil_plural(len(checkout_files) - 10, 'more file')}")

    if not args.force:
        try:
            response = input("\nProceed? [y/N]: ").strip().lower()
            if response not in ('y', 'yes'):
                print("Checkout cancelled.")
                return False
        except (EOFError, KeyboardInterrupt):
            print("\nCheckout cancelled.")
            return False

    # Perform the checkout
    try:
        subprocess.run(["git", "checkout", "HEAD", "--"]
                       + clutil_literal_pathspecs(checkout_files),
                       check=True)
        print("Successfully reverted "
              f"{clutil_plural(len(checkout_files), 'file')} to HEAD state.")


        # Show summary by changelist. Only files in HEAD were reverted;
        # untracked, new and missing files were skipped above.
        print("\nFiles reverted by changelist:")
        for name in args.names:
            if name in changelists and changelists[name]:
                reverted_count = sum(1 for f in changelists[name]
                                     if f in in_head)
                if reverted_count > 0:
                    print(f"  {name}: {clutil_plural(reverted_count, 'file')}")

        # Delete changelists if --delete flag is set
        if args.delete:
            deleted_any = False
            for name in args.names:
                if name in changelists:
                    del changelists[name]
                    print(f"Deleted changelist '{name}'")
                    deleted_any = True

            if deleted_any:
                clutil_save(changelists)

    except subprocess.CalledProcessError as error:
        clutil_report_failure("Could not revert the files", error)
        clutil_print_error("Some files may not have been reverted.")
        return False

    # Changelists that were not found are reported above; the existing
    # ones are still reverted, but the command as a whole has failed.
    return not missing_changelists


def cl_remove(args: argparse.Namespace) -> bool:
    """
    Removes one or more files from any changelists they are part of.

    Args:
        args: argparse.Namespace with 'files' attribute.
    """
    changelists = clutil_load()
    removed = []
    failed = False

    git_root = clutil_get_git_root()
    stored = ([f for files in changelists.values() for f in files]
              if clutil_ignores_case() else None)
    for file in args.files:
        sanitized = clutil_sanitize_path(file, git_root)
        if sanitized is None:
            clutil_print_error(f"Error: Skipping invalid or unsafe path: '{file}'")
            failed = True
            continue
        if stored is not None:
            sanitized = clutil_match_case(sanitized, stored, git_root)

        found = False
        for name, files in changelists.items():
            if sanitized in files:
                files.remove(sanitized)
                removed.append(sanitized)
                print(f"Removed '{sanitized}' from changelist '{name}'")
                found = True
                break  # Stop after first match

        if not found:
            clutil_print_error(f"Error: '{file}' was not found in any changelist.")
            failed = True

    if removed:
        clutil_save(changelists)
    return not failed


def cl_delete(args: argparse.Namespace) -> bool:
    """
    Deletes one or more changelists by name, or all with --all.
    """
    changelists = clutil_load()
    stashes = clutil_load_stashes()

    if args.all and args.names:
        clutil_print_error("Error: Cannot specify changelist names and --all together.")
        return False

    if args.all:
        if not changelists:
            print("No changelists to delete.")
            return True
        count = len(changelists)
        changelists.clear()
        clutil_save(changelists)
        print(f"Deleted all {count} changelists.")
        return True

    if not args.names:
        clutil_print_error("Error: No changelist names provided.")
        return False

    deleted = False
    missing = False
    for name in args.names:
        if name in changelists:
            del changelists[name]
            print(f"Deleted changelist '{name}'")
            deleted = True
        elif name in stashes:
            clutil_print_error(f"Error: Changelist '{name}' is stashed. "
                               "Delete only removes active changelists.")
            clutil_print_error(f"Unstash it first with 'git cl unstash {name}'.")
            missing = True
        else:
            clutil_print_error(f"Error: Changelist '{name}' not found.")
            missing = True

    if deleted:
        clutil_save(changelists)
    return not missing


def cl_prune(args: argparse.Namespace) -> bool:
    """
    Removes stale entries from all active changelists.

    See clutil_prune() for what counts as stale.

    With --exit-code, the exit code tells whether stale entries were
    found, following 'git diff --exit-code': 0 if there were none, 1 if
    there were (removed, or only listed with --dry-run), and 2 on error.
    Errors in git-cl normally exit with 1, so they are mapped to 2 here to
    keep them apart from 'stale entries found'.

    Args:
        args: argparse.Namespace with 'dry_run', 'quiet' and 'exit_code'
              attributes.
    """
    if not getattr(args, 'exit_code', False):
        clutil_prune(args)
        return True

    try:
        total = clutil_prune(args)
    except SystemExit as error:
        if error.code not in (0, None):
            sys.exit(2)
        raise
    sys.exit(1 if total else 0)


def clutil_prune(args: argparse.Namespace) -> int:
    """
    Removes stale entries from all active changelists.

    An entry is stale when Git reports nothing for it: the file has no
    staged or unstaged changes, or it no longer exists and is unknown to
    Git (shown as [XX] in 'git cl status'). Such entries typically remain
    after committing with plain 'git commit'.

    Entries with any Git status (modified, staged, deleted, untracked,
    conflicted) are kept. A directory entry is kept as long as any file
    inside it has a Git status. Only changelist metadata is changed, never
    file contents.

    Stashed changelists are kept, except for orphaned records whose Git
    stash no longer exists (see clutil_find_orphaned_stashes()). Removing
    such a record frees its files for other changelists. Each orphaned
    record counts as one stale entry.

    Does nothing when the GIT_CL_NO_PRUNE environment variable is set,
    which 'git cl commit' does for its own commit (see NO_PRUNE_ENV).

    Args:
        args: argparse.Namespace with 'dry_run' and 'quiet' attributes.

    Returns:
        The number of stale entries found (removed, or only listed in a
        dry run).
    """
    if os.environ.get(NO_PRUNE_ENV):
        return 0

    changelists = clutil_load()
    git_root = clutil_get_git_root()

    # Untracked files are listed individually so that an untracked file
    # inside an untracked directory still counts as having a status.
    status_map = clutil_get_file_status_map(
                                            include_untracked=True)

    def is_stale(stored_path: str) -> bool:
        if stored_path in status_map:
            return False
        if clutil_is_real_dir(git_root / stored_path):
            prefix = stored_path.rstrip("/") + "/"
            return not any(path.startswith(prefix) for path in status_map)
        return True

    pruned: dict[str, list[str]] = {}
    for name, files in changelists.items():
        stale = [f for f in files if is_stale(f)]
        if stale:
            pruned[name] = stale

    stashes = clutil_load_stashes()
    orphaned = clutil_find_orphaned_stashes(stashes)

    if not pruned and not orphaned:
        if not args.quiet:
            print("Nothing to prune.")
        return 0

    # Changelists whose every entry is stale will end up empty
    emptied = sorted(name for name, stale in pruned.items()
                     if len(stale) == len(changelists[name]))

    verb = "Would remove" if args.dry_run else "Removed"
    cwd = Path.cwd().resolve()
    total = sum(len(stale) for stale in pruned.values()) + len(orphaned)

    if not args.quiet:
        for name in orphaned:
            print(f"{verb} stashed changelist '{name}': its Git stash no "
                  "longer exists")
            files = [shlex.quote(_relpath(git_root / f, cwd))
                     for f in stashes[name]["files"]]
            if files and not args.dry_run:
                print(f"  To group its files again: git cl add {name} "
                      + " ".join(files))
    for name, stale in sorted(pruned.items()):
        if not args.quiet:
            for stored_path in stale:
                display = _relpath(git_root / stored_path, cwd)
                print(f"{verb} '{display}' from changelist '{name}'")
        if not args.dry_run:
            changelists[name] = [f for f in changelists[name]
                                 if f not in stale]

    if args.dry_run:
        if not args.quiet:
            for name in emptied:
                print(f"Changelist '{name}' would become empty "
                      "and be deleted.")
            print(f"Dry run: {total} stale entr"
                  f"{'y' if total == 1 else 'ies'} found, nothing changed.")
        return total

    if orphaned:
        for name in orphaned:
            del stashes[name]
        clutil_save_stashes(stashes)

    # clutil_save omits empty changelists, so emptied ones disappear here
    if pruned:
        clutil_save(changelists)

    if not args.quiet:
        for name in emptied:
            print(f"Deleted empty changelist '{name}'")
        print(f"Pruned {total} stale entr{'y' if total == 1 else 'ies'}.")
    return total


def cl_commit(args: argparse.Namespace) -> bool:
    """
    Commits all tracked files in one or more changelists as a single
    commit, then optionally deletes them.

    If any named changelist does not exist, nothing is committed.
    Duplicate names are ignored.

    Args:
        args: argparse.Namespace with 'names', 'message'/'file',
              and 'keep' attributes.
    """
    changelists = clutil_load()
    names = clutil_resolve_changelist_names(args.names, changelists,
                                            "committed")
    if names is None:
        return False

    git_root = clutil_get_git_root()

    # Fetch git status once and reuse for all files in the changelists
    status_map = clutil_get_file_status_map()

    if clutil_refuse_on_merge_conflict(status_map, "commit"):
        return False

    to_commit, files_by_name = clutil_collect_changelist_files(
        names, changelists, git_root, status_map,
        lambda path: path in status_map
        and not clutil_is_file_untracked_cached(path, status_map))

    label = clutil_changelist_label(names)
    if not to_commit:
        print(f"No tracked files with changes to commit in {label}.")
        clutil_hint_untracked(names, changelists, status_map)
        return True

    commit_message = clutil_resolve_commit_message(args)
    if not commit_message:
        return False

    # Point out renames of which only one side is being committed
    for line in clutil_note_split_renames(names, changelists,
                                          clutil_get_renames(), git_root):
        print(line)

    try:
        # Keep a post-commit hook running 'git cl prune' from acting on
        # this commit (see NO_PRUNE_ENV)
        subprocess.run(["git", "commit", "-m", commit_message, "--"]
                       + clutil_literal_pathspecs(to_commit), check=True,
                       env={**os.environ, NO_PRUNE_ENV: "1"})
    except subprocess.CalledProcessError as error:
        clutil_report_failure(f"Could not commit {label}", error)
        clutil_print_error("The changelist is kept. Fix the problem reported "
                           "above, then run the command again.")
        return False

    clutil_print_files_by_changelist("Committed tracked files from", names,
                                     to_commit, files_by_name)

    if not args.keep:
        for name in names:
            del changelists[name]
        clutil_save(changelists)
        print(f"Deleted {label}")
    else:
        print(f"Kept {label}")
    return True


def cl_stash(args: argparse.Namespace, quiet: bool = False) -> bool:
    """
    Stash all unstaged changes for files in specified changelist(s).
    Supports --all to stash all active changelists.
    Tracks source branch for better workflow support.

    Accepts files with:
    - Unstaged changes (modified, deleted)
    - Newly added to index (staged additions)
    - Untracked files (if explicitly in changelist)

    Args:
        args: argparse.Namespace with 'name'
              (or None for --all), 'all' attributes.
        quiet: If True, suppress verbose output for workflow contexts

    Returns:
        True if the stash succeeded (for --all: all changelists were
        stashed), False otherwise. Callers such as cl_branch rely on
        this to detect failures that are otherwise only printed.
    """
    changelists = clutil_load()
    stashes = clutil_load_stashes()

    if not clutil_has_commits():
        clutil_print_error("Error: Cannot stash before the first commit; Git "
                           "needs a commit to stash changes against.")
        clutil_print_error("Commit something first, for example: "
                           "git cl commit <changelist> -m 'Initial commit'")
        return False

    if clutil_refuse_on_intent_to_add(clutil_get_file_status_map(),
                                      clutil_get_git_root()):
        return False

    # Handle --all flag
    if getattr(args, 'all', False):
        success_count, total = clutil_stash_all_changelists(changelists,
                                                            quiet=quiet)
        return success_count == total

    # Handle single changelist stash
    name = args.name

    # Validate preconditions
    error_msg = clutil_validate_stash_preconditions(name, changelists, stashes)
    if error_msg:
        clutil_print_error(error_msg)
        return False

    git_root = clutil_get_git_root()
    files = changelists[name]

    # Check that files exist and categorize them
    existing_files, missing_files = clutil_prepare_stash_files(files, git_root)

    # Get file statuses and categorize
    status_map = clutil_get_file_status_map()

    if clutil_refuse_on_merge_conflict(status_map, "stash"):
        return False

    categorization = clutil_categorize_files_for_stash(
        existing_files, missing_files, status_map, git_root
    )
    file_categories, stashable_files, unstashable_files = categorization

    # Report categorization and check if we can proceed
    if not clutil_report_stash_categorization(file_categories,
                                              unstashable_files, name):
        return False

    if not stashable_files:
        if not quiet:
            print(f"No stashable files found in changelist '{name}'.")
        return False

    # Prepare files for git stash command
    current_branch = clutil_get_current_branch()

    files_for_git, untracked_files_for_git = clutil_prepare_files_for_git_stash(
        stashable_files, file_categories, git_root
    )

    # Generate the unique stash message once and thread it through both the
    # git stash push and the metadata save. Generating it independently in
    # each place risks the two timestamps differing across a second boundary,
    # leaving cl-stashes.json with a message that doesn't match git's stash.
    stash_message = clutil_create_unique_stash_message(name)

    # Execute git stash with safe directory handling
    try:
        with clutil_safe_stash_context(
                git_root, files_for_git,
                untracked_files_for_git) as (safe_files, safe_untracked_files):
            stash_ref = clutil_execute_git_stash(name, stash_message,
                                                 safe_files,
                                                 safe_untracked_files)
    except (subprocess.CalledProcessError, ValueError):
        return False

    # Save metadata atomically
    try:
        clutil_save_stash_metadata_atomic(
            name, stash_message, stash_ref, files,
            file_categories, changelists, stashes
        )
    except ClutilSaveError:
        clutil_handle_stash_failure(name, stash_ref, stash_message,
                                    safe_files, safe_untracked_files,
                                    git_root)
        return False

    # Success! Print appropriate message based on context
    if not quiet:
        clutil_print_stash_success(name, stashable_files, current_branch)
    return True


def cl_unstash(args: argparse.Namespace, quiet: bool = False) -> bool:
    """
    Restore a stashed changelist to the working directory.
    Enforces clean branch workflow by default.
    Supports --all to unstash all stashed changelists.

    Args:
        args: argparse.Namespace with 'name' (or None for --all),
            'force', and 'all' attributes.
        quiet: If True, suppress verbose output for workflow contexts

    Returns:
        True if the unstash succeeded (for --all: all changelists were
        unstashed), False otherwise. Callers such as cl_branch rely on
        this to detect failures that are otherwise only printed.
    """
    stashes = clutil_load_stashes()
    changelists = clutil_load()

    status_map = clutil_get_file_status_map()
    if clutil_refuse_on_merge_conflict(status_map, "unstash"):
        return False

    # Handle --all flag
    if getattr(args, 'all', False):
        success_count, total = clutil_unstash_all_changelists(
            stashes, getattr(args, 'force', False))
        return success_count == total

    # Handle single changelist unstash
    name = args.name
    # Stashes are keyed by the changelist name itself
    base_name = stash_key = name

    # A record whose stash is gone can never be unstashed. Say so before
    # any other check, which would only point to the working directory.
    if stash_key in stashes and clutil_find_orphaned_stashes(
            {stash_key: stashes[stash_key]}):
        clutil_print_error(f"Error: Cannot unstash changelist '{base_name}'.")
        clutil_print_orphaned_stash_hint(base_name)
        return False

    # Validate environment and get stash data
    error_msg, stash_data = clutil_validate_unstash_environment(
        base_name, stash_key, stashes, changelists,
        getattr(args, 'force', False),
        getattr(args, 'ignore_untracked', False)
    )
    if error_msg or stash_data is None:
        clutil_print_error(error_msg or f"Error: No stash record for "
                           f"'{base_name}'.")
        return False

    stash_ref = stash_data["stash_ref"]
    files = stash_data["files"]
    git_root = clutil_get_git_root()

    # Refuse if unstashing would overwrite local changes
    if not clutil_check_and_report_conflicts(files, git_root, base_name,
                                             getattr(args, 'force', False)):
        return False

    # Verify stash still exists and update reference
    stash_ref = clutil_verify_and_update_stash_ref(base_name, stash_ref,
                                                   stash_data)
    if not stash_ref:
        return False

    result = clutil_apply_stash(stash_ref, base_name, stash_data)
    if result == "failed":
        return False
    if result == "conflict":
        # The changes are applied. Restore the changelist so that a second
        # unstash cannot apply them again; the stash itself is kept.
        clutil_update_unstash_metadata(base_name, stash_key, files,
                                       changelists, stashes, quiet=True)
        return False

    # Success - update metadata (suppress verbose output in quiet mode)
    return clutil_update_unstash_metadata(base_name, stash_key, files,
                                          changelists, stashes, quiet=quiet)


def cl_branch(args: argparse.Namespace) -> bool:
    """
    Create a new branch with changelist workflow: stash all changelists,
    create branch, unstash specified changelist.

    This automates the common workflow of:
    1. Stash all active changelists to clean working directory
    2. Create a new branch from current HEAD (or specified base)
    3. Unstash the specified changelist to the new branch

    Args:
        args: argparse.Namespace with 'changelist_name', optional 'branch_name',
              and optional 'from_branch' attributes.
    """
    changelists = clutil_load()
    stashes = clutil_load_stashes()

    changelist_name = args.changelist_name
    branch_name = getattr(args, 'branch_name', None) or changelist_name

    # Validate changelist exists and is active
    error_msg = clutil_validate_branch_preconditions(changelist_name,
                                                     changelists, stashes)
    if error_msg:
        clutil_print_error(error_msg)
        return False

    if not clutil_has_commits():
        clutil_print_error("Error: Cannot create a branch before the first "
                           "commit. Commit something first, for example:")
        clutil_print_error(f"  git cl commit {changelist_name} -m 'Initial "
                           "commit'")
        return False

    # Check the name with Git's rules before anything is stashed
    if subprocess.run(["git", "check-ref-format", "--branch", branch_name],
                      capture_output=True, text=True,
                      check=False).returncode != 0:
        clutil_print_error(f"Error: '{branch_name}' is not a valid branch "
                           "name.")
        clutil_print_error("See 'git help check-ref-format' for the rules.")
        return False

    # Check if branch already exists
    if clutil_check_branch_exists(branch_name):
        clutil_print_error(f"Error: Branch '{branch_name}' already exists.")
        clutil_print_error(f"Use a different branch name: git cl br "
                           f"{changelist_name} <new-branch-name>")
        return False

    # Check for uncommitted changes not in any changelist
    git_root = clutil_get_git_root()
    unassigned_changes = clutil_check_unassigned_changes(changelists, git_root)

    if unassigned_changes:
        submodules = clutil_get_submodule_paths(git_root)
        changed_submodules = [f for f in unassigned_changes if f in submodules]
        unassigned_files = [f for f in unassigned_changes
                            if f not in submodules]
        status_map = clutil_get_file_status_map()
        clutil_print_error("Error: There are uncommitted changes not in any "
                           "changelist:")
        for file_path in unassigned_changes[:10]:  # Show first 10
            clutil_print_error(f"  [{status_map[file_path]}] {file_path}")
        if len(unassigned_changes) > 10:
            clutil_print_error("  ... and "
                               f"{clutil_plural(len(unassigned_changes) - 10, 'more file')}")
        if unassigned_files:
            clutil_print_error("\nPlease assign these files to changelists first:")
            clutil_print_error("  git cl add <changelist-name> "
                               f"{' '.join(unassigned_files[:3])}")
        if changed_submodules:
            names = " ".join(shlex.quote(p) for p in changed_submodules)
            clutil_print_error("\nSubmodules point to a new commit. Changelists "
                               "cannot contain submodules;")
            clutil_print_error("record the new commit, or reset the submodule:")
            clutil_print_error(f"  git add {names} && git commit")
            clutil_print_error(f"  git submodule update -- {names}")
        return False

    # Get current branch for messaging
    current_branch = clutil_get_current_branch()
    if not current_branch:
        clutil_print_error("Error: Cannot create branch from detached HEAD state.")
        clutil_print_error("Switch to a branch first: git checkout <branch-name>")
        return False

    # Determine base branch
    base_branch = getattr(args, 'from_branch', None) or current_branch

    # Collect active changelists for the workflow
    active_changelists = {name: files for name, files in changelists.items() if files}

    # Pre-flight: every active changelist must be fully stashable.
    # cl_stash refuses changelists containing clean or staged-only files,
    # so a single such changelist would otherwise abort the workflow
    # halfway through and leave the repo inconsistent (issue #51).
    # Fail fast here, before any state is mutated.
    status_map = clutil_get_file_status_map()
    if clutil_refuse_on_intent_to_add(status_map, git_root):
        return False
    problems = clutil_validate_changelists_stashable(
        active_changelists, git_root, status_map)
    if problems:
        clutil_report_branch_problems(problems, status_map, git_root, args)
        return False

    print(f"Creating branch '{branch_name}' with changelist '{changelist_name}'")
    if len(active_changelists) > 1:
        print(f"Stashing {len(active_changelists)} active changelists...")

    # Step 1: Stash all active changelists (quietly)
    try:
        success_count, total = clutil_stash_all_changelists(
            active_changelists, quiet=True)
    except (subprocess.CalledProcessError,
            OSError, json.JSONDecodeError) as error:
        clutil_report_failure("Could not stash the changelists", error)
        clutil_print_error("Branch creation aborted.")
        return False

    # The pre-flight check should make this unreachable, but git stash
    # can still fail for other reasons (I/O errors, hooks, ...). Never
    # create the branch on top of a partially stashed working directory.
    if success_count != total:
        clutil_print_error(f"Error: Only {success_count}/{total} changelists could "
                           "be stashed.")
        clutil_print_error("Branch creation aborted. Restoring stashed changelists...")
        clutil_handle_branch_creation_failure()
        return False

    # Step 2: Create the new branch
    try:
        # git checkout already reports "Switched to a new branch ..."
        clutil_create_branch(branch_name, base_branch, current_branch)
    except subprocess.CalledProcessError as error:
        clutil_report_failure(f"Could not create branch '{branch_name}'",
                              error)
        clutil_print_error("Restoring the stashed changelists...")
        clutil_handle_branch_creation_failure()
        return False

    # Step 3: Unstash the target changelist (quietly)
    try:
        if not clutil_unstash_changelist(changelist_name):
            clutil_print_error(f"Error: Branch '{branch_name}' was created but "
                               f"restoring changelist '{changelist_name}' failed.")
            clutil_print_error(f"Changelist '{changelist_name}' is still "
                               "stashed. Resolve the problem above, then "
                               f"run: git cl unstash {changelist_name}")
            return False

        # Single success message
        file_count = len(changelists.get(changelist_name, []))
        print(f"Restored changelist '{changelist_name}' "
              f"({clutil_plural(file_count, 'file')})")
        still_stashed = sorted(clutil_load_stashes())
        if still_stashed:
            print(f"Still stashed: {', '.join(still_stashed)} "
                  "(restore with: git cl unstash <name>)")
        return True

    except (subprocess.CalledProcessError,
            OSError, json.JSONDecodeError) as error:
        clutil_report_failure(
            f"Could not unstash changelist '{changelist_name}'", error)
        clutil_print_error(f"Branch '{branch_name}' was created but "
                           "changelist restore failed.")
        clutil_print_error(f"Changelist '{changelist_name}' is still "
                           "stashed. Resolve the problem above, then "
                           f"run: git cl unstash {changelist_name}")
        return False


def cl_help(args: argparse.Namespace) -> bool:
    """
    Displays the main help message using argparse's built-in formatting.
    """
    args.parser.print_help()
    return True


# =============================================================================
# MAIN ENTRY POINT
# =============================================================================


def main() -> None:
    """
    Entry point for the git-cl command-line interface.

    Parses command-line arguments and dispatches to the appropriate
    subcommand handler (e.g., add, remove, stage, commit, etc.).
    """

    # File and changelist names in messages must not reach the terminal
    # with control characters in them. Output of Git commands that write
    # to the terminal directly, such as 'git diff', is left to Git.
    sys.stdout = ClutilEscapingStream(sys.stdout)
    sys.stderr = ClutilEscapingStream(sys.stderr)

    parser = argparse.ArgumentParser(
        prog='git-cl',
        usage='git cl <command> [<args>]',
        description=(
            "git-cl: A Git subcommand for managing named changelists \n"
            "        Group files into logical changelists before staging "
            "or committing.\n\n"
            "        NOTE: Commit/stage commands only operate on tracked files;"
            "\n              untracked files in changelists are safely "
            "ignored."),
        epilog=(
            "Example usage:\n"
            "    git cl add my-feature file1.py file2.py\n"
            "    git cl status\n"
            "    git cl commit my-feature -m 'Implement feature'\n\n"
            "About: \n"
            f"    Version: {__version__}\n"
            "    GitHub:  https://github.com/BHFock/git-cl \n"
            "    DOI:     https://doi.org/10.5281/zenodo.18722077"),
        formatter_class=argparse.RawTextHelpFormatter,
        add_help=False)

    parser.add_argument(
        '--version',
        action='version',
        version=f'git-cl {__version__}',
        help=argparse.SUPPRESS)

    subparsers = parser.add_subparsers(dest='command', title='Commands',
                                       prog='git cl', metavar='<command>')

    # ADD
    add_parser = subparsers.add_parser('add', aliases=['a'],
                                       help='Add files to a named changelist',
                                       description=(
                                           "Add one or more files to a named "
                                           "changelist. If the changelist "
                                           "does not exist, it will be "
                                           "created automatically."))
    add_parser.add_argument('name', metavar='CHANGELIST',
                            help='Name of the changelist to add files to')
    add_parser.add_argument('files', metavar='FILE', nargs='+',
                            help=("One or more files to include "
                                  "in the changelist"))
    add_parser.set_defaults(func=cl_add)

    # REMOVE
    remove_parser = subparsers.add_parser('remove', aliases=['r', 'rm'],
                                          help=("Remove files from any "
                                                "changelist"),
                                          description=("Remove files from "
                                                       "the changelists they "
                                                       "belong to."))
    remove_parser.add_argument('files', metavar='FILE', nargs='+',
                               help=("One or more files to remove "
                                     "from changelists"))
    remove_parser.set_defaults(func=cl_remove)

    # DELETE
    delete_parser = subparsers.add_parser('delete', aliases=['del'],
                                          help=("Delete one or more "
                                                "changelists"),
                                          description=(
                                              "Delete one or more changelists "
                                              "by name, or remove all with "
                                              "--all."))
    delete_parser.add_argument('names', metavar='CHANGELIST', nargs='*',
                               help=("One or more changelists to delete "
                                     "(required unless --all is used)"))
    delete_parser.add_argument('--all', action='store_true',
                               help='Delete all changelists')
    delete_parser.set_defaults(func=cl_delete)

    # PRUNE
    prune_parser = subparsers.add_parser('prune',
                                         help=("Remove files without "
                                               "changes from all "
                                               "changelists"),
                                         description=(
                                             "Remove stale entries from all "
                                             "changelists: files with no "
                                             "staged or unstaged changes, "
                                             "and files that no longer "
                                             "exist and are unknown to Git. "
                                             "These typically remain after "
                                             "committing with plain 'git "
                                             "commit'. Changelists left "
                                             "empty are deleted. Only "
                                             "changelist metadata is "
                                             "changed, never file contents. "
                                             "Stashed changelists are kept, "
                                             "unless their Git stash no "
                                             "longer exists. Files excluded by "
                                             ".gitignore have no Git status "
                                             "and are removed as well. Does "
                                             "nothing during 'git cl "
                                             "commit', so that a post-commit "
                                             "hook only acts on commits made "
                                             "outside git-cl."))
    prune_parser.add_argument('-n', '--dry-run', action='store_true',
                              help=("Show what would be removed without "
                                    "changing anything"))
    prune_parser.add_argument('-q', '--quiet', action='store_true',
                              help=("Suppress output (useful in a "
                                    "post-commit hook)"))
    prune_parser.add_argument('--exit-code', action='store_true',
                              help=("Exit with 1 if stale entries were "
                                    "found and 0 if not; errors exit "
                                    "with 2"))
    prune_parser.set_defaults(func=cl_prune)

    # STATUS
    status_parser = subparsers.add_parser('status', aliases=['s', 'st'],
                                          help=("Show file changes grouped by "
                                                "changelist"),
                                          description=(
                                              "Show file changes grouped by "
                                              "changelist. Unassigned files "
                                              "appear under 'No Changelist'."))
    status_parser.add_argument('names', metavar='CHANGELIST', nargs='*',
                               help=("Optional list of changelists to show "
                                     "(default: all)"))
    status_parser.add_argument('--include-no-cl', action='store_true',
                               help=("When filtering by changelist names, "
                                     "also show files not assigned to any "
                                     "changelist"))
    status_parser.add_argument('--all', action='store_true',
                               help=("No longer needed: all Git status "
                                     "codes are shown. Accepted for "
                                     "existing scripts"))
    status_parser.add_argument('--no-untracked', action='store_true',
                               help='Hide untracked files (??) from output')
    status_parser.add_argument('--no-color', action='store_true',
                               help='Disable coloured output')
    status_parser.set_defaults(func=cl_status)

    # DIFF
    diff_parser = subparsers.add_parser('diff',
                                        help=("Show git diff for one or more "
                                              "changelists"),
                                        description=(
                                            "Show unified diff for the files "
                                            "in one or more changelists. "
                                            "By default, shows unstaged "
                                            "changes (like `git diff`). "
                                            "Use --staged for staged changes, "
                                            "or --both to show both."))
    diff_parser.add_argument('names', metavar='CHANGELIST', nargs='+',
                             help='One or more changelists to diff')
    diff_parser.add_argument('--staged', action='store_true',
                             help='Show staged changes (index vs HEAD)')
    diff_parser.add_argument('--both', action='store_true',
                             help='Show both unstaged and staged diffs')
    diff_parser.set_defaults(func=cl_diff)

    # CHECKOUT
    checkout_parser = subparsers.add_parser('checkout', aliases=['co'],
                                            help=("Checkout (revert) files "
                                                  "from changelists"),
                                            description=(
                                                "Revert files in one or more "
                                                "changelists to their HEAD "
                                                "state, discarding both "
                                                "staged and unstaged changes "
                                                "in those files. Deleted "
                                                "files are restored. Files "
                                                "that are not in HEAD, "
                                                "untracked or newly added, "
                                                "are left as they are: "
                                                "checkout never deletes a "
                                                "file. Files without changes "
                                                "are left out. By default, "
                                                "asks for "
                                                "confirmation before "
                                                "proceeding."))
    checkout_parser.add_argument('names', metavar='CHANGELIST', nargs='+',
                                 help='One or more changelists to checkout')
    checkout_parser.add_argument('--delete', action='store_true',
                                 help='Delete the changelist after checkout')
    checkout_parser.add_argument('-f', '--force', action='store_true',
                                 help='Skip confirmation prompt')
    checkout_parser.set_defaults(func=cl_checkout)

    # STAGE
    stage_parser = subparsers.add_parser('stage',
                                         help=("Stage tracked files from "
                                               "one or more changelists"),
                                         description=(
                                             "Stage the tracked files with "
                                             "changes from the specified "
                                             "changelist(s). Untracked files "
                                             "and files without changes are "
                                             "left out. If any named "
                                             "changelist does not exist, "
                                             "nothing is staged. "
                                             "By default, the changelists "
                                             "are kept unless --delete is "
                                             "used."))
    stage_parser.add_argument('names', metavar='CHANGELIST', nargs='+',
                              help='Name(s) of the changelist(s) to stage')
    stage_parser.add_argument('--delete', action='store_true',
                              help='Delete the changelist(s) after staging')
    stage_parser.set_defaults(func=cl_stage)

    # UNSTAGE
    unstage_parser = subparsers.add_parser('unstage',
                                           help=("Unstage tracked files from "
                                                 "one or more changelists"),
                                           description=(
                                               "Unstage all staged files from "
                                               "the specified changelist(s), "
                                               "moving them back to unstaged "
                                               "state in the working "
                                               "directory. If any named "
                                               "changelist does not exist, "
                                               "nothing is unstaged. By "
                                               "default, the changelists are "
                                               "kept unless --delete is "
                                               "used."))
    unstage_parser.add_argument('names', metavar='CHANGELIST', nargs='+',
                                help='Name(s) of the changelist(s) to unstage')
    unstage_parser.add_argument('--delete', action='store_true',
                                help=('Delete the changelist(s) after '
                                      'unstaging'))
    unstage_parser.set_defaults(func=cl_unstage)

    # COMMIT
    commit_parser = subparsers.add_parser('commit', aliases=['ci'],
                                          help=("Commit tracked files from "
                                                "one or more changelists "
                                                "(auto-stages, ignores "
                                                "untracked)"),
                                          description=(
                                              "Stage and commit the tracked "
                                              "files with changes from the "
                                              "specified changelist(s) as a "
                                              "single commit. Untracked "
                                              "files and files without "
                                              "changes are left out. If any "
                                              "named changelist does not "
                                              "exist, nothing is committed. "
                                              "By default, the changelists "
                                              "are deleted after committing "
                                              "unless --keep is used."))
    commit_parser.add_argument('names', metavar='CHANGELIST', nargs='+',
                               help='Name(s) of the changelist(s) to commit')
    msg_group = commit_parser.add_mutually_exclusive_group(required=True)
    msg_group.add_argument('-m', '--message',
                           help='Commit message')
    msg_group.add_argument('-F', '--file',
                           help='Read commit message from file')
    commit_parser.add_argument('--keep', action='store_true',
                               help='Keep the changelist(s) after committing')
    commit_parser.set_defaults(func=cl_commit)

    # STASH
    stash_parser = subparsers.add_parser('stash', aliases=['sh'],
                                         help='Stash changes in changelist(s)',
                                         description=(
                                             "Stash the changes of the files "
                                             "in the specified changelist: "
                                             "unstaged changes, newly added "
                                             "files and untracked files. A "
                                             "changelist with files that "
                                             "have only staged changes or "
                                             "no changes is refused. Use "
                                             "--all to stash all active "
                                             "changelists at once."))
    stash_group = stash_parser.add_mutually_exclusive_group(required=True)
    stash_group.add_argument('name', nargs='?', metavar='CHANGELIST',
                             help='Name of the changelist to stash')
    stash_group.add_argument('--all', action='store_true',
                             help='Stash all active changelists')
    stash_parser.set_defaults(func=cl_stash)

    # UNSTASH
    unstash_parser = subparsers.add_parser('unstash', aliases=['us'],
                                           help=("Restore stashed "
                                                 "changelist(s)"),
                                           description=(
                                               "Restore a stashed changelist "
                                               "to the working directory, "
                                               "including which changes were "
                                               "staged. Refuses if files of "
                                               "the changelist have changes "
                                               "in the working directory, in "
                                               "a detached HEAD state, or on "
                                               "another branch with "
                                               "uncommitted changes; --force "
                                               "skips these checks. "
                                               "Use --all to unstash all "
                                               "stashed changelists to the "
                                               "current branch."))
    unstash_group = unstash_parser.add_mutually_exclusive_group(required=True)
    unstash_group.add_argument('name', nargs='?', metavar='CHANGELIST',
                               help='Name of the changelist to unstash')
    unstash_group.add_argument('--all', action='store_true',
                               help='Unstash all stashed changelists')
    unstash_parser.add_argument('--force', action='store_true',
                                help=("Skip the checks for changes in the "
                                      "working directory and the branch"))
    unstash_parser.set_defaults(func=cl_unstash)

    # BRANCH
    branch_parser = subparsers.add_parser('branch', aliases=['br'],
                                          help=("Create a branch from a "
                                                "changelist"),
                                          description=(
                                              "Automate the changelist-to-"
                                              "branch workflow: stash all "
                                              "active changelists, create a "
                                              "new branch, and unstash the "
                                              "specified changelist to the "
                                              "new branch. The other "
                                              "changelists stay stashed; "
                                              "restore them later with 'git "
                                              "cl unstash'. Refuses if "
                                              "changes are not assigned to a "
                                              "changelist, or if a "
                                              "changelist cannot be "
                                              "stashed."))
    branch_parser.add_argument('changelist_name', metavar='CHANGELIST',
                               help=("Name of the changelist to "
                                     "create a branch for"))
    branch_parser.add_argument('branch_name',
                               metavar='BRANCH', nargs='?',
                               help=("Name of the new branch "
                                     "(defaults to changelist name)"))
    branch_parser.add_argument('--from', dest='from_branch',
                               metavar='BASE_BRANCH',
                               help=("Create branch from specified base "
                                     "branch (default: current branch)"))
    branch_parser.set_defaults(func=cl_branch)

    # HELP
    help_parser = subparsers.add_parser('help',
                                        help='Show this help message',
                                        description=(
                                            "Show a summary of the "
                                            "available git-cl commands."))
    help_parser.set_defaults(func=cl_help, parser=parser)

    args = parser.parse_args()

    # If no command was provided, show help
    if args.command is None:
        parser.print_help()
        return

    # Provide parser to all commands in case needed
    if not hasattr(args, 'parser'):
        args.parser = parser

    # Every command returns True on success and False on failure, so that
    # scripts can rely on the exit code (0 or 1). argparse itself exits
    # with 2 on invalid usage before a command runs.
    # git-cl changes to the repository root for some Git commands. Make
    # relative paths in Git's environment absolute first, so that they
    # keep pointing to the same place.
    for variable in ("GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE",
                     "GIT_COMMON_DIR"):
        value = os.environ.get(variable)
        if value and not os.path.isabs(value):
            os.environ[variable] = os.path.abspath(value)

    try:
        succeeded = args.func(args)
        sys.stdout.flush()
    except (ClutilSaveError, ClutilLoadError):
        # The reason has already been printed by the save or load function.
        sys.exit(1)
    except BrokenPipeError:
        # The reader closed the pipe early, as in 'git cl status | head'.
        # Exit quietly like git does. Output still buffered for the closed
        # pipe is sent to os.devnull, so that Python does not report the
        # same error again when it flushes stdout at exit.
        devnull = os.open(os.devnull, os.O_WRONLY)
        os.dup2(devnull, sys.stdout.fileno())
        sys.exit(1)
    sys.exit(0 if succeeded else 1)


if __name__ == '__main__':
    main()
