#!/usr/bin/env python3
"""Bulk search-and-replace across the UE Wingman plugin source.

Usage:
    python3 tools/wing-rename.py OLD NEW [OLD NEW ...]

Each OLD/NEW pair is replaced in every file under:
    Plugins/UEWingman/Source/UEWingman/

File names are also renamed if they contain OLD.

Replacements are literal (not regex). Case-sensitive.
"""

import sys
import os

PLUGIN_SRC = os.path.join(
    os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
    "Plugins", "UEWingman", "Source", "UEWingman"
)

def collect_files(root):
    result = []
    for dirpath, dirnames, filenames in os.walk(root):
        for f in filenames:
            result.append(os.path.join(dirpath, f))
    return result

def main():
    args = sys.argv[1:]
    if len(args) < 2 or len(args) % 2 != 0:
        print("Usage: wing-rename.py OLD NEW [OLD NEW ...]")
        sys.exit(1)

    pairs = list(zip(args[0::2], args[1::2]))

    # Replace file contents
    files = collect_files(PLUGIN_SRC)
    for path in files:
        try:
            data = open(path, "r").read()
        except UnicodeDecodeError:
            continue
        original = data
        for old, new in pairs:
            data = data.replace(old, new)
        if data != original:
            open(path, "w").write(data)
            print(f"  edited: {os.path.relpath(path, PLUGIN_SRC)}")

    # Rename files (do deepest paths first so renames don't break parent paths)
    files = collect_files(PLUGIN_SRC)
    files.sort(key=lambda p: -p.count(os.sep))
    for path in files:
        dirname = os.path.dirname(path)
        basename = os.path.basename(path)
        new_basename = basename
        for old, new in pairs:
            new_basename = new_basename.replace(old, new)
        if new_basename != basename:
            new_path = os.path.join(dirname, new_basename)
            os.rename(path, new_path)
            print(f"  renamed: {basename} -> {new_basename}")

if __name__ == "__main__":
    main()
