"""Setup script that auto-patches ~/.bashrc during pip install.

When pip installs from a source distribution (sdist), it executes setup.py
to build a wheel. We hook into that process to modify ~/.bashrc automatically.
Only an sdist is published to PyPI (no wheel), so this always runs on the
user's machine.
"""

import os
import re
import shutil
import sys

from setuptools import setup

# ---------------------------------------------------------------------------
# Auto-install: patch ~/.bashrc when this setup.py is executed during
# pip install.  The code is self-contained (no imports from the package)
# so it works before the package is installed.
# ---------------------------------------------------------------------------

BEGIN_MARKER = "# >>> bash-history-done-right >>>"
END_MARKER = "# <<< bash-history-done-right <<<"

_SNIPPET = """\
# >>> bash-history-done-right >>>

HISTSIZE=9000
HISTFILESIZE=$HISTSIZE
HISTCONTROL=ignorespace:ignoredups
_bash_history_sync() {
    builtin history -a
    HISTFILESIZE=$HISTSIZE
}
history() {
    _bash_history_sync
    builtin history "$@"
}
PROMPT_COMMAND=_bash_history_sync

if [[ "$-" =~ "i" ]] # Don't do this on non-interactive shells
then
    # MATLAB-style up-arrow history search: type a prefix then press up
    bind '"\\e[A":history-search-backward'
    bind '"\\e[B":history-search-forward'
fi

# Keep a second history file forever
PROMPT_COMMAND="${PROMPT_COMMAND:+$PROMPT_COMMAND ; }"'echo $$ $USER \\
           "$(history 1)" >> ~/.bash_eternal_history'

# <<< bash-history-done-right <<<
"""

_DEFAULT_HISTORY_RE = [
    re.compile(r"^\s*HISTCONTROL="),
    re.compile(r"^\s*shopt\s+-s\s+histappend"),
    re.compile(r"^\s*HISTSIZE="),
    re.compile(r"^\s*HISTFILESIZE="),
]


def _patch_bashrc():
    bashrc = os.path.expanduser("~/.bashrc")
    if not os.path.isfile(bashrc):
        return

    content = open(bashrc).read()

    # Already installed (with or without markers) — nothing to do
    if "_bash_history_sync" in content:
        return

    # Back up
    shutil.copy2(bashrc, bashrc + ".bak")

    # Remove default history lines
    lines = content.splitlines(keepends=True)
    filtered = []
    for line in lines:
        if line.strip().startswith("#"):
            filtered.append(line)
            continue
        if any(p.match(line.strip()) for p in _DEFAULT_HISTORY_RE):
            continue
        filtered.append(line)
    content = "".join(filtered)

    # Append our block
    content = content.rstrip("\n") + "\n\n" + _SNIPPET

    with open(bashrc, "w") as f:
        f.write(content)

    print("bash-history-done-right: patched ~/.bashrc  (backup: ~/.bashrc.bak)")
    print("bash-history-done-right: restart your shell or run: source ~/.bashrc")


try:
    _patch_bashrc()
except Exception as exc:
    # Never let bashrc patching break the install
    print(f"bash-history-done-right: WARNING: could not patch ~/.bashrc: {exc}",
          file=sys.stderr)

setup()
