#!/usr/bin/env python3
"""
Runtime FBX Importer - project fix after the plugin rename
==========================================================
Runtime FBX Import was renamed to Runtime FBX Importer (plugin folder, module and
content mount point: RuntimeFBXImport -> RuntimeFBXImporter).

This script updates an EXISTING Unreal project that used the old plugin so it works with the new one:

  1. .uproject          plugin entry RuntimeFBXImport -> RuntimeFBXImporter
  2. Config/DefaultEngine.ini
                        adds [CoreRedirects] package redirects, so Blueprints, data assets and maps that
                        reference the old C++ classes or the old plugin content load without broken references
  3. Source/ (C++ projects only)
                        RuntimeFBXImport -> RuntimeFBXImporter in .Build.cs, #include and *_API names
  4. Plugins/RuntimeFBXImport (old copy inside the project)
                        moved to the backup folder; put the NEW plugin in Plugins/RuntimeFBXImporter
  5. Optional --clean   deletes the project's Binaries and Intermediate folders (always safe, UE rebuilds them)

Everything it changes is first copied to <project>/_RuntimeFBXImporter_Fix_Backup_<time>/.
Your Content folder is never edited. Make a copy or commit to source control first anyway.

Usage (Python 3.8+, close the Unreal Editor first):
    python FixRuntimeFBXImporterRename.py "D:/Projects/MyGame"
    python FixRuntimeFBXImporterRename.py "D:/Projects/MyGame" --dry-run     (show what would change)
    python FixRuntimeFBXImporterRename.py "D:/Projects/MyGame" --clean       (also clear Binaries/Intermediate)

The path may be the project folder or the .uproject file itself.
After running: install the new Runtime FBX Importer from Fab (Fab library > Install to project, or copy the
plugin folder into <project>/Plugins/RuntimeFBXImporter), open the project and let it recompile,
then in the Content Browser use File > Save All once so the assets are saved with the new names.
"""
import argparse
import json
import re
import shutil
import sys
import time
from pathlib import Path

OLD, NEW = "RuntimeFBXImport", "RuntimeFBXImporter"
RX = re.compile(r"RuntimeFBXImport(?!er)")
RX_API = re.compile(r"RUNTIMEFBXIMPORT_API")
REDIRECT_LINES = [
    '+PackageRedirects=(OldName="/Script/RuntimeFBXImport",NewName="/Script/RuntimeFBXImporter")',
    '+PackageRedirects=(OldName="/RuntimeFBXImport/",NewName="/RuntimeFBXImporter/",MatchSubstring=true)',
]
SRC_EXT = {".cs", ".h", ".hpp", ".cpp", ".inl", ".ini", ".uplugin", ".json", ".txt"}


def read_text(p):
    raw = p.read_bytes()
    bom = raw.startswith(b"\xef\xbb\xbf")
    try:
        return raw.decode("utf-8-sig"), "utf-8", bom
    except UnicodeDecodeError:
        return raw.decode("cp1252"), "cp1252", False


def write_text(p, s, enc, bom):
    p.write_bytes((b"\xef\xbb\xbf" if bom else b"") + s.encode(enc))


class Fixer:
    def __init__(self, project_dir, uproject, dry, clean):
        self.dir, self.uproject, self.dry, self.clean = project_dir, uproject, dry, clean
        self.backup = project_dir / ("_RuntimeFBXImporter_Fix_Backup_" + time.strftime("%Y%m%d_%H%M%S"))
        self.log = []

    def say(self, msg):
        print(msg)
        self.log.append(msg)

    def backup_file(self, p):
        if self.dry:
            return
        dst = self.backup / p.relative_to(self.dir)
        dst.parent.mkdir(parents=True, exist_ok=True)
        shutil.copy2(p, dst)

    def fix_uproject(self):
        data = json.loads(read_text(self.uproject)[0])
        plugins = data.get("Plugins", [])
        names = [pl.get("Name") for pl in plugins]
        if OLD not in names:
            self.say(f"[uproject] no '{OLD}' plugin entry (already fixed or not used): {self.uproject.name}")
            return
        self.backup_file(self.uproject)
        out, seen_new = [], NEW in names
        for pl in plugins:
            if pl.get("Name") == OLD:
                if seen_new:
                    continue  # new entry already exists, drop the old one
                pl = dict(pl, Name=NEW)
                seen_new = True
            out.append(pl)
        data["Plugins"] = out
        if not self.dry:
            self.uproject.write_text(json.dumps(data, indent="\t") + "\n", encoding="utf-8")
        self.say(f"[uproject] plugin entry {OLD} -> {NEW}")

    def fix_engine_ini(self):
        ini = self.dir / "Config" / "DefaultEngine.ini"
        if not ini.exists():
            if not self.dry:
                ini.parent.mkdir(exist_ok=True)
            text, enc, bom = "", "utf-8", False
        else:
            text, enc, bom = read_text(ini)
        missing = [l for l in REDIRECT_LINES if l not in text]
        if not missing:
            self.say("[ini] redirects already present in Config/DefaultEngine.ini")
            return
        if ini.exists():
            self.backup_file(ini)
        nl = "\r\n" if "\r\n" in text else "\n"
        m = re.search(r"^\[CoreRedirects\][ \t]*(\r?\n|$)", text, re.M)
        if m:  # add under the existing section header
            head = text[: m.end()] if m.group(1) else text[: m.end()] + nl
            text = head + nl.join(missing) + nl + text[m.end():]
        else:
            text = text.rstrip() + (nl + nl if text.strip() else "") + "[CoreRedirects]" + nl + nl.join(missing) + nl
        if not self.dry:
            write_text(ini, text, enc, bom)
        self.say(f"[ini] added {len(missing)} redirect line(s) to Config/DefaultEngine.ini")

    def fix_source(self):
        src = self.dir / "Source"
        if not src.is_dir():
            self.say("[source] no Source folder (Blueprint-only project): nothing to do")
            return
        n = 0
        for p in src.rglob("*"):
            if not p.is_file() or p.suffix.lower() not in SRC_EXT:
                continue
            s, enc, bom = read_text(p)
            t = RX_API.sub("RUNTIMEFBXIMPORTER_API", RX.sub(NEW, s))
            if t != s:
                self.backup_file(p)
                if not self.dry:
                    write_text(p, t, enc, bom)
                self.say(f"[source] updated {p.relative_to(self.dir)}")
                n += 1
        if n == 0:
            self.say("[source] no references to the old module name in Source/")

    def move_old_plugin(self):
        old = self.dir / "Plugins" / OLD
        if not old.is_dir():
            self.say(f"[plugin] no Plugins/{OLD} folder inside the project")
            return
        dst = self.backup / "Plugins" / OLD
        self.say(f"[plugin] moving old Plugins/{OLD} to the backup folder (install the new plugin in Plugins/{NEW})")
        if not self.dry:
            dst.parent.mkdir(parents=True, exist_ok=True)
            shutil.move(str(old), str(dst))

    def clean_build(self):
        for name in ("Binaries", "Intermediate"):
            d = self.dir / name
            if d.is_dir():
                self.say(f"[clean] deleting {name}/")
                if not self.dry:
                    shutil.rmtree(d, ignore_errors=True)

    def run(self):
        self.say(f"Project: {self.uproject}")
        if self.dry:
            self.say("DRY RUN: nothing is written")
        self.fix_uproject()
        self.fix_engine_ini()
        self.fix_source()
        self.move_old_plugin()
        if self.clean:
            self.clean_build()
        if not self.dry and self.backup.exists():
            self.say(f"Backup of changed files: {self.backup}")
        self.say("")
        self.say("Next: install the new Runtime FBX Importer plugin, open the project, let it compile,")
        self.say("then File > Save All in the editor so assets are saved with the new names.")


def main():
    ap = argparse.ArgumentParser(description="Fix a project for the Runtime FBX Import -> Runtime FBX Importer rename.")
    ap.add_argument("project", help="project folder or .uproject file")
    ap.add_argument("--dry-run", action="store_true", help="show changes without writing")
    ap.add_argument("--clean", action="store_true", help="also delete the project's Binaries and Intermediate folders")
    a = ap.parse_args()
    p = Path(a.project).expanduser().resolve()
    if p.is_file() and p.suffix.lower() == ".uproject":
        uproject, d = p, p.parent
    elif p.is_dir():
        found = sorted(p.glob("*.uproject"))
        if not found:
            sys.exit(f"No .uproject found in {p}")
        uproject, d = found[0], p
    else:
        sys.exit(f"Not found: {p}")
    Fixer(d, uproject, a.dry_run, a.clean).run()


if __name__ == "__main__":
    main()
