#!/usr/bin/env python3
"""searchrep — search/replace across a tree with preview, backups, and a change count.
Usage: searchrep [--apply] [--backup] [--include GLOB] [--fixed] PATTERN REPLACEMENT [PATH ...]
Dry-run preview is the default: every hit is shown with before/after context and
a per-file change count. Nothing is written until --apply; --backup keeps .bak
copies of every file that changes.
"""
import argparse, fnmatch, os, re, sys


def iter_files(paths, include, exclude):
    for base in paths:
        if os.path.isfile(base):
            yield base
        else:
            for root, dirs, files in os.walk(base):
                dirs[:] = [d for d in dirs if not any(fnmatch.fnmatch(d, pat) for pat in exclude)]
                for name in files:
                    if include and not any(fnmatch.fnmatch(name, pat) for pat in include):
                        continue
                    if any(fnmatch.fnmatch(name, pat) for pat in exclude):
                        continue
                    yield os.path.join(root, name)


def main(argv=None):
    ap = argparse.ArgumentParser(prog="searchrep",
        description="Search/replace across a tree with preview, backups, and a change count.")
    ap.add_argument("pattern", help="regex to search for (or literal text with --fixed)")
    ap.add_argument("replacement", help="replacement text (regex backrefs like \\1 work)")
    ap.add_argument("paths", nargs="*", default=["."], help="files or directories (default: .)")
    ap.add_argument("--apply", action="store_true", help="actually write the changes (default: preview only)")
    ap.add_argument("--backup", action="store_true", help="keep a .bak copy of each changed file")
    ap.add_argument("--include", action="append", default=[], help="only files matching this glob (repeatable)")
    ap.add_argument("--exclude", action="append", default=[".git", "__pycache__", "*.bak"],
                    help="skip names matching this glob (repeatable)")
    ap.add_argument("--fixed", action="store_true", help="treat PATTERN as literal text, not regex")
    ap.add_argument("--selftest", action="store_true", help="run a built-in self-test and exit")
    argv_list = list(argv) if argv is not None else sys.argv[1:]
    if "--selftest" in argv_list:
        return selftest()
    a = ap.parse_args(argv)
    if a.selftest:
        return selftest()
    try:
        rx = re.compile(re.escape(a.pattern) if a.fixed else a.pattern)
    except re.error as e:
        print(f"searchrep: bad pattern: {e}", file=sys.stderr)
        return 2
    total_files = total_hits = changed_files = 0
    for path in iter_files(a.paths, a.include, a.exclude):
        try:
            with open(path, encoding="utf-8", errors="strict") as fh:
                text = fh.read()
        except (OSError, UnicodeDecodeError):
            continue
        hits = rx.findall(text)
        if not hits:
            continue
        total_files += 1
        total_hits += len(hits)
        new_text, n = rx.subn(a.replacement, text)
        print(f"== {path}: {n} change(s) ==")
        for i, line in enumerate(text.splitlines(), 1):
            if rx.search(line):
                print(f"  {i}: - {line.strip()[:100]}")
                print(f"  {i}: + {rx.sub(a.replacement, line).strip()[:100]}")
        if a.apply:
            if a.backup:
                with open(path + ".bak", "w", encoding="utf-8") as fh:
                    fh.write(text)
            with open(path, "w", encoding="utf-8") as fh:
                fh.write(new_text)
            changed_files += 1
    mode = "applied" if a.apply else "preview (use --apply to write)"
    print(f"searchrep: {total_hits} change(s) in {total_files} file(s) — {mode}"
          + (f", {changed_files} file(s) written" if a.apply else ""))
    return 0


def selftest():
    import tempfile, os
    with tempfile.TemporaryDirectory() as d:
        p = os.path.join(d, "a.txt")
        open(p, "w").write("foo bar foo\nfoo baz\n")
        assert main(["foo", "qux", p]) == 0
        assert open(p).read().startswith("foo"), "preview must not write"
        assert main(["--apply", "--backup", "foo", "qux", p]) == 0
        assert open(p).read() == "qux bar qux\nqux baz\n", open(p).read()
        assert os.path.exists(p + ".bak")
        assert main(["--fixed", "qux", "foo", p]) == 0
    print("searchrep selftest: PASS")
    return 0


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