from pathlib import Path
import importlib.util
import sys


APP = Path(__file__).resolve().parent
V29_PATH = APP / "racecore_studio_v29.py"
if str(APP) not in sys.path:
    sys.path.insert(0, str(APP))

spec = importlib.util.spec_from_file_location("racecore_v29_for_v30", V29_PATH)
v29 = importlib.util.module_from_spec(spec)
spec.loader.exec_module(v29)

from core.keyboard_controls import action_for_key, clamped


class StudioV30(v29.StudioV29):
    """Snelle precisiebediening voor het geselecteerde preview-object."""

    def __init__(self):
        super().__init__()
        self.title("RaceCore Livery Studio v3.0 - Precision Controls")

    def build_layout(self):
        super().build_layout()
        header = self.winfo_children()[0]
        tk = v29.v28.v27.v26.v25.tk
        for child in header.winfo_children():
            if isinstance(child, tk.Label) and "Livery Studio" in child.cget("text"):
                child.configure(text="Livery Studio  v3.0")

        self.direct_hint.configure(
            text="SLEEP | HOEK = SCHALEN | RONDJE = DRAAIEN | SNAP = STRAK"
        )
        viewer = self.preview_label.master
        self.keyboard_hint = tk.Label(
            viewer,
            text="PIJLEN = 1  |  SHIFT + PIJL = 10  |  CTRL+D = KOPIE  |  DEL = WISSEN",
            font=("Segoe UI", 8, "bold"), fg="#BAE6FD", bg="#0B1730",
            padx=10, pady=6,
        )
        self.keyboard_hint.place(x=20, y=50)
        self.keyboard_hint.lift()
        self.preview_label.bind("<KeyPress>", self.keyboard_shortcut, add="+")

    def keyboard_shortcut(self, event):
        action = action_for_key(event.keysym, event.state)
        if action is None:
            return None
        if action.name == "undo":
            self.undo()
            self.schedule_preview()
            return "break"
        if action.name == "redo":
            self.redo()
            self.schedule_preview()
            return "break"
        if action.name == "duplicate":
            self.sidebar_duplicate()
            selection = self.layer_sidebar_tree.selection()
            if selection:
                self.preview_selected_uid = selection[0].removeprefix("layer:")
                self.preview_selected_instance = 0
                self.show_selection_overlay()
                self.preview_label.focus_set()
            return "break"
        if action.name == "delete":
            selected_uid = self.preview_selected_uid
            self.sidebar_delete()
            if selected_uid and self.resolve_layer_uid(selected_uid) is None:
                self.preview_selected_uid = None
                self.preview_selected_instance = 0
            return "break"
        if action.name == "nudge":
            self.nudge_selected(action.dx, action.dy)
            return "break"
        return None

    def nudge_selected(self, dx, dy):
        target = self.selected_transform_target()
        if target is None:
            self.status.set("Kies eerst een zichtbaar, ontgrendeld object")
            return False
        reference, layer, placed = target
        instance = placed.instance_index
        origin_x, origin_y = self.drag_origin(reference.kind, layer, instance)
        if reference.kind == "logo":
            self.move_logo(layer, instance, origin_x, origin_y, dx, dy)
        else:
            layer["centerX"] = clamped(origin_x + dx, 0, 4096)
            direction = -1 if layer.get("paired", False) and instance > 0 else 1
            layer["centerY"] = clamped(origin_y + direction * dy, 0, 4096)

        self.active_snap_guides = {"x": None, "y": None}
        self.record_state()
        self.autosave()
        self.schedule_preview()
        self.refresh_layer_sidebar(reference.uid)
        self.show_selection_overlay()
        self.preview_label.focus_set()
        self.status.set(f"Fijn verplaatst: {dx:+d}, {dy:+d}")
        return True


if __name__ == "__main__":
    StudioV30().mainloop()
