bl_info = {
    "name": "Katana Inu Arcade Import",
    "author": "Katana Inu",
    "version": (1, 0, 0),
    "blender": (3, 6, 0),
    "location": "File > Import > Katana Inu Arcade (.glb URL)",
    "description": "Import a 3D model from the Katana Inu Arcade by its GLB link.",
    "category": "Import-Export",
}

# Lädt eine GLB-Datei über ihre Adresse (3D Workshop / Library der Arcade) und importiert sie
# mit Blenders eingebautem glTF-Importer. Kein Konto, kein Schlüssel — nur die Datei-Adresse.
import os
import tempfile
import urllib.request

import bpy
from bpy.props import StringProperty


class KATANA_OT_import_url(bpy.types.Operator):
    bl_idname = "import_scene.katana_inu_arcade"
    bl_label = "Katana Inu Arcade (.glb URL)"
    bl_options = {"REGISTER", "UNDO"}

    url: StringProperty(name="GLB link", description="Copy the model's GLB link from the Arcade", default="")

    def invoke(self, context, event):
        return context.window_manager.invoke_props_dialog(self, width=520)

    def execute(self, context):
        url = self.url.strip()
        if not url.lower().startswith("https://"):
            self.report({"ERROR"}, "Paste an https:// link to a .glb file")
            return {"CANCELLED"}
        ziel = None
        try:
            req = urllib.request.Request(url, headers={"User-Agent": "KatanaInuArcadeBlender/1.0"})
            with urllib.request.urlopen(req, timeout=60) as r:
                daten = r.read()
            if daten[:4] != b"glTF":
                self.report({"ERROR"}, "That link is not a GLB file")
                return {"CANCELLED"}
            with tempfile.NamedTemporaryFile(suffix=".glb", delete=False) as f:
                ziel = f.name
                f.write(daten)
            bpy.ops.import_scene.gltf(filepath=ziel)
        except Exception as e:  # Netzwerk/HTTP-Fehler verständlich melden
            self.report({"ERROR"}, f"Import failed: {e}")
            return {"CANCELLED"}
        finally:
            if ziel and os.path.exists(ziel):
                os.remove(ziel)
        self.report({"INFO"}, "Model imported from Katana Inu Arcade")
        return {"FINISHED"}


def menu(self, context):
    self.layout.operator(KATANA_OT_import_url.bl_idname, text="Katana Inu Arcade (.glb URL)")


def register():
    bpy.utils.register_class(KATANA_OT_import_url)
    bpy.types.TOPBAR_MT_file_import.append(menu)


def unregister():
    bpy.types.TOPBAR_MT_file_import.remove(menu)
    bpy.utils.unregister_class(KATANA_OT_import_url)
