# Katana Inu Arcade Import for Unreal Engine 5 (Editor Python).
# Needs the built-in plugins "Python Editor Script Plugin" and "glTF Importer" (both ship with UE5).
# Run: Tools > Execute Python Script… and pick this file, or in the Output Log (Python):
#   py "C:/path/katana_inu_arcade_unreal.py" https://…/model.glb
import os
import sys
import tempfile
import urllib.request

import unreal


def importieren(url: str, ziel_ordner: str = "/Game/KatanaInu") -> None:
    if not url.lower().startswith("https://"):
        unreal.log_error("Katana Inu: paste an https:// link to a .glb file")
        return
    req = urllib.request.Request(url, headers={"User-Agent": "KatanaInuArcadeUnreal/1.0"})
    with urllib.request.urlopen(req, timeout=60) as r:
        daten = r.read()
    if daten[:4] != b"glTF":
        unreal.log_error("Katana Inu: that link is not a GLB file")
        return
    datei = None
    try:
        with tempfile.NamedTemporaryFile(suffix=".glb", delete=False) as f:
            datei = f.name
            f.write(daten)
        task = unreal.AssetImportTask()
        task.filename = datei
        task.destination_path = ziel_ordner
        task.automated = True
        task.save = True
        unreal.AssetToolsHelpers.get_asset_tools().import_asset_tasks([task])
        pfade = task.get_editor_property("imported_object_paths")
        if not pfade:
            unreal.log_error("Katana Inu: nothing was imported into " + ziel_ordner)
        else:
            unreal.log(f"Katana Inu: imported {len(pfade)} object(s) into {ziel_ordner}")
    finally:
        if datei and os.path.exists(datei):
            os.remove(datei)


if __name__ == "__main__":
    link = sys.argv[1] if len(sys.argv) > 1 else ""
    if not link:
        unreal.log_error("Katana Inu: usage — py katana_inu_arcade_unreal.py https://…/model.glb")
    else:
        importieren(link)
