#!/usr/bin/env python3
"""
PNG Cropper with Transparency
A simple GUI tool to crop transparent PNGs with zoom, movable/resizable selection.

Requirements:
    pip install Pillow

On Linux you may also need: sudo apt install python3-tk

Usage:
    python3 png_cropper.py
"""

import os
import tkinter as tk
from tkinter import filedialog, messagebox, ttk
from PIL import Image, ImageTk


class PNGCropper:
    def __init__(self, root):
        self.root = root
        self.root.title("PNG Cropper (Transparency Preserving)")
        self.root.geometry("1100x800")
        self.root.minsize(800, 600)

        # State
        self.original_image = None      # Full PIL Image (RGBA)
        self.display_image = None       # Scaled for display
        self.photo = None               # ImageTk.PhotoImage
        self.zoom = 1.0
        self.image_path = None
        self.output_dir = None
        self.crop_counter = 1

        # Selection rectangle (in canvas/display coordinates)
        self.rect_id = None
        self.handles = []               # list of canvas item ids for resize handles
        self.drag_mode = None           # None, 'draw', 'move', 'resize-xx'
        self.drag_start = None
        self.rect_coords = None         # (x1, y1, x2, y2) in display coords

        self._build_ui()
        self._bind_keys()

    def _build_ui(self):
        # Top toolbar
        toolbar = ttk.Frame(self.root, padding=6)
        toolbar.pack(side=tk.TOP, fill=tk.X)

        ttk.Button(toolbar, text="Open PNG", command=self.open_file).pack(side=tk.LEFT, padx=4)
        ttk.Button(toolbar, text="Zoom In (+)", command=lambda: self.zoom_by(1.25)).pack(side=tk.LEFT, padx=4)
        ttk.Button(toolbar, text="Zoom Out (−)", command=lambda: self.zoom_by(0.8)).pack(side=tk.LEFT, padx=4)
        ttk.Button(toolbar, text="Select", command=self.start_select).pack(side=tk.LEFT, padx=4)
        ttk.Button(toolbar, text="Clear Selection", command=self.clear_selection).pack(side=tk.LEFT, padx=4)
        ttk.Button(toolbar, text="Crop & Save", command=self.crop_and_save).pack(side=tk.LEFT, padx=4)

        self.status_var = tk.StringVar(value="Open a PNG to begin.  Use + / − to zoom.")
        ttk.Label(toolbar, textvariable=self.status_var).pack(side=tk.RIGHT, padx=8)

        # Canvas with scrollbars
        canvas_frame = ttk.Frame(self.root)
        canvas_frame.pack(fill=tk.BOTH, expand=True, padx=4, pady=4)

        self.canvas = tk.Canvas(canvas_frame, bg="#2b2b2b", highlightthickness=0)
        h_scroll = ttk.Scrollbar(canvas_frame, orient=tk.HORIZONTAL, command=self.canvas.xview)
        v_scroll = ttk.Scrollbar(canvas_frame, orient=tk.VERTICAL, command=self.canvas.yview)
        self.canvas.configure(xscrollcommand=h_scroll.set, yscrollcommand=v_scroll.set)

        self.canvas.grid(row=0, column=0, sticky="nsew")
        v_scroll.grid(row=0, column=1, sticky="ns")
        h_scroll.grid(row=1, column=0, sticky="ew")
        canvas_frame.grid_rowconfigure(0, weight=1)
        canvas_frame.grid_columnconfigure(0, weight=1)

        # Mouse bindings
        self.canvas.bind("<ButtonPress-1>", self.on_mouse_down)
        self.canvas.bind("<B1-Motion>", self.on_mouse_drag)
        self.canvas.bind("<ButtonRelease-1>", self.on_mouse_up)
        self.canvas.bind("<Motion>", self.on_mouse_move)

    def _bind_keys(self):
        self.root.bind("<plus>", lambda e: self.zoom_by(1.25))
        self.root.bind("<equal>", lambda e: self.zoom_by(1.25))   # = key (often with +)
        self.root.bind("<minus>", lambda e: self.zoom_by(0.8))
        self.root.bind("<KP_Add>", lambda e: self.zoom_by(1.25))
        self.root.bind("<KP_Subtract>", lambda e: self.zoom_by(0.8))

    # ------------------------------------------------------------------ UI actions
    def open_file(self):
        path = filedialog.askopenfilename(
            title="Open PNG",
            filetypes=[("PNG images", "*.png"), ("All files", "*.*")]
        )
        if not path:
            return
        try:
            img = Image.open(path).convert("RGBA")
        except Exception as e:
            messagebox.showerror("Error", f"Could not open image:\n{e}")
            return

        self.original_image = img
        self.image_path = path
        base_dir = os.path.dirname(path)
        self.output_dir = os.path.join(base_dir, "crop_")
        os.makedirs(self.output_dir, exist_ok=True)
        # Continue numbering from whatever already exists in crop_
        self.crop_counter = 1
        try:
            existing = [f for f in os.listdir(self.output_dir)
                        if f.startswith("crop_") and f.endswith(".png")]
            nums = []
            for f in existing:
                try:
                    nums.append(int(f[5:8]))  # crop_NNN.png
                except ValueError:
                    pass
            if nums:
                self.crop_counter = max(nums) + 1
        except OSError:
            pass
        self.zoom = 1.0
        self.clear_selection()
        self._update_display()
        self._update_status()

    def zoom_by(self, factor):
        if self.original_image is None:
            return
        self.zoom = max(0.1, min(10.0, self.zoom * factor))
        # Keep selection mapped correctly by scaling existing rect if present
        if self.rect_coords:
            cx = (self.rect_coords[0] + self.rect_coords[2]) / 2
            cy = (self.rect_coords[1] + self.rect_coords[3]) / 2
            w = (self.rect_coords[2] - self.rect_coords[0]) * factor
            h = (self.rect_coords[3] - self.rect_coords[1]) * factor
            self.rect_coords = (cx - w/2, cy - h/2, cx + w/2, cy + h/2)
        self._update_display()
        self._redraw_selection()

    def start_select(self):
        if self.original_image is None:
            messagebox.showinfo("Info", "Open an image first.")
            return
        self.clear_selection()
        self.drag_mode = "draw"
        self.status_var.set("Drag on the image to draw a selection rectangle.")

    def clear_selection(self):
        if self.rect_id:
            self.canvas.delete(self.rect_id)
            self.rect_id = None
        for h in self.handles:
            self.canvas.delete(h)
        self.handles.clear()
        self.rect_coords = None
        self.drag_mode = None

    def crop_and_save(self):
        if self.original_image is None or not self.rect_coords:
            messagebox.showinfo("Info", "Draw a selection first.")
            return

        # Convert display coords → original image coords
        x1, y1, x2, y2 = self.rect_coords
        ox1 = int(round(min(x1, x2) / self.zoom))
        oy1 = int(round(min(y1, y2) / self.zoom))
        ox2 = int(round(max(x1, x2) / self.zoom))
        oy2 = int(round(max(y1, y2) / self.zoom))

        # Clamp to image bounds
        w, h = self.original_image.size
        ox1 = max(0, min(ox1, w - 1))
        oy1 = max(0, min(oy1, h - 1))
        ox2 = max(ox1 + 1, min(ox2, w))
        oy2 = max(oy1 + 1, min(oy2, h))

        cropped = self.original_image.crop((ox1, oy1, ox2, oy2))

        # Ensure output directory exists
        if self.output_dir:
            os.makedirs(self.output_dir, exist_ok=True)

        # Find next available number
        while True:
            filename = f"crop_{self.crop_counter:03d}.png"
            out_path = os.path.join(self.output_dir or ".", filename)
            if not os.path.exists(out_path):
                break
            self.crop_counter += 1

        try:
            cropped.save(out_path, "PNG")
            self.crop_counter += 1
            self.status_var.set(f"Saved: crop_/{filename}  ({ox2-ox1}×{oy2-oy1})")
            messagebox.showinfo("Saved", f"Cropped image saved as:\n{out_path}")
        except Exception as e:
            messagebox.showerror("Error", f"Could not save:\n{e}")

    # ------------------------------------------------------------------ Display
    def _update_display(self):
        if self.original_image is None:
            return
        w, h = self.original_image.size
        new_w = max(1, int(w * self.zoom))
        new_h = max(1, int(h * self.zoom))
        self.display_image = self.original_image.resize((new_w, new_h), Image.Resampling.LANCZOS)
        self.photo = ImageTk.PhotoImage(self.display_image)

        self.canvas.delete("image")
        self.canvas.create_image(0, 0, anchor=tk.NW, image=self.photo, tags="image")
        self.canvas.configure(scrollregion=(0, 0, new_w, new_h))
        self._update_status()

    def _update_status(self):
        if self.original_image is None:
            return
        w, h = self.original_image.size
        name = os.path.basename(self.image_path) if self.image_path else ""
        self.status_var.set(f"{name}  |  {w}×{h}  |  zoom {self.zoom:.2f}x  |  next: crop_/crop_{self.crop_counter:03d}.png")

    # ------------------------------------------------------------------ Selection drawing / interaction
    def _redraw_selection(self):
        if not self.rect_coords:
            return
        x1, y1, x2, y2 = self.rect_coords
        if self.rect_id:
            self.canvas.coords(self.rect_id, x1, y1, x2, y2)
        else:
            self.rect_id = self.canvas.create_rectangle(
                x1, y1, x2, y2,
                outline="#00ff88", width=2, dash=(4, 2), tags="selection"
            )
        self._draw_handles()

    def _draw_handles(self):
        for h in self.handles:
            self.canvas.delete(h)
        self.handles.clear()
        if not self.rect_coords:
            return
        x1, y1, x2, y2 = self.rect_coords
        # Order: NW, N, NE, E, SE, S, SW, W
        points = [
            (x1, y1), ((x1+x2)/2, y1), (x2, y1),
            (x2, (y1+y2)/2), (x2, y2), ((x1+x2)/2, y2),
            (x1, y2), (x1, (y1+y2)/2)
        ]
        size = 8
        for px, py in points:
            hid = self.canvas.create_rectangle(
                px - size/2, py - size/2, px + size/2, py + size/2,
                fill="#00ff88", outline="white", width=1, tags="handle"
            )
            self.handles.append(hid)

    def _hit_test_handle(self, x, y, threshold=10):
        """Return handle index (0-7) or None."""
        if not self.rect_coords:
            return None
        x1, y1, x2, y2 = self.rect_coords
        points = [
            (x1, y1), ((x1+x2)/2, y1), (x2, y1),
            (x2, (y1+y2)/2), (x2, y2), ((x1+x2)/2, y2),
            (x1, y2), (x1, (y1+y2)/2)
        ]
        for i, (px, py) in enumerate(points):
            if abs(x - px) < threshold and abs(y - py) < threshold:
                return i
        return None

    def _point_in_rect(self, x, y):
        if not self.rect_coords:
            return False
        x1, y1, x2, y2 = self.rect_coords
        return min(x1, x2) <= x <= max(x1, x2) and min(y1, y2) <= y <= max(y1, y2)

    def on_mouse_down(self, event):
        # Convert event coords to canvas coords (account for scrolling)
        x = self.canvas.canvasx(event.x)
        y = self.canvas.canvasy(event.y)

        handle = self._hit_test_handle(x, y)
        if handle is not None:
            self.drag_mode = f"resize-{handle}"
            self.drag_start = (x, y, self.rect_coords)
            return

        if self._point_in_rect(x, y):
            self.drag_mode = "move"
            self.drag_start = (x, y, self.rect_coords)
            return

        # Start new selection
        self.clear_selection()
        self.drag_mode = "draw"
        self.drag_start = (x, y)
        self.rect_coords = (x, y, x, y)
        self._redraw_selection()

    def on_mouse_drag(self, event):
        if not self.drag_mode or not self.drag_start:
            return
        x = self.canvas.canvasx(event.x)
        y = self.canvas.canvasy(event.y)

        if self.drag_mode == "draw":
            sx, sy = self.drag_start
            self.rect_coords = (sx, sy, x, y)
            self._redraw_selection()

        elif self.drag_mode == "move":
            sx, sy, (ox1, oy1, ox2, oy2) = self.drag_start
            dx = x - sx
            dy = y - sy
            self.rect_coords = (ox1 + dx, oy1 + dy, ox2 + dx, oy2 + dy)
            self._redraw_selection()

        elif self.drag_mode.startswith("resize-"):
            idx = int(self.drag_mode.split("-")[1])
            sx, sy, (ox1, oy1, ox2, oy2) = self.drag_start
            # Map handle index to which edges to move
            # 0:NW 1:N 2:NE 3:E 4:SE 5:S 6:SW 7:W
            nx1, ny1, nx2, ny2 = ox1, oy1, ox2, oy2
            if idx in (0, 1, 2):   # top
                ny1 = y
            if idx in (4, 5, 6):   # bottom
                ny2 = y
            if idx in (2, 3, 4):   # right
                nx2 = x
            if idx in (0, 6, 7):   # left
                nx1 = x
            # Ensure minimum size
            if abs(nx2 - nx1) < 5:
                nx2 = nx1 + 5 if nx2 > nx1 else nx1 - 5
            if abs(ny2 - ny1) < 5:
                ny2 = ny1 + 5 if ny2 > ny1 else ny1 - 5
            self.rect_coords = (nx1, ny1, nx2, ny2)
            self._redraw_selection()

    def on_mouse_up(self, event):
        self.drag_mode = None
        self.drag_start = None
        if self.rect_coords:
            # Normalize so x1<x2, y1<y2 for easier handling later
            x1, y1, x2, y2 = self.rect_coords
            self.rect_coords = (min(x1, x2), min(y1, y2), max(x1, x2), max(y1, y2))
            self._redraw_selection()

    def on_mouse_move(self, event):
        # Optional: change cursor based on hover (simple version)
        x = self.canvas.canvasx(event.x)
        y = self.canvas.canvasy(event.y)
        handle = self._hit_test_handle(x, y)
        if handle is not None:
            cursors = ["top_left_corner", "top_side", "top_right_corner",
                       "right_side", "bottom_right_corner", "bottom_side",
                       "bottom_left_corner", "left_side"]
            try:
                self.canvas.config(cursor=cursors[handle])
            except Exception:
                pass
        elif self._point_in_rect(x, y):
            self.canvas.config(cursor="fleur")
        else:
            self.canvas.config(cursor="")


def main():
    root = tk.Tk()
    # Use a nicer theme if available
    try:
        style = ttk.Style()
        if "clam" in style.theme_names():
            style.theme_use("clam")
    except Exception:
        pass
    app = PNGCropper(root)
    root.mainloop()


if __name__ == "__main__":
    main()
