import tkinter as tk
import threading
import queue

def select_area(coord_queue):
    """
    Opens a selection overlay to allow the user to select a region on the screen.
    Once the region is selected, the coordinates are passed to the queue.

    Args:
        coord_queue (queue.Queue): A queue to store the selected coordinates.
    """
    coords = []

    # Create a new Tkinter root for the selection overlay
    root = tk.Tk()
    root.withdraw()  # Hide the root window

    # Create overlay window for region selection
    overlay = tk.Toplevel(root)
    overlay.title("Selection Overlay")
    overlay.attributes('-topmost', True)  # Always on top
    overlay.attributes('-alpha', 0.3)  # Semi-transparent background (30% opacity)
    overlay.overrideredirect(True)  # Remove window decorations (borderless)

    sw = root.winfo_screenwidth()
    sh = root.winfo_screenheight()
    overlay.geometry(f"{sw}x{sh}+0+0")

    canvas = tk.Canvas(overlay, cursor="cross", bd=0, highlightthickness=0)
    canvas.pack(fill=tk.BOTH, expand=True)

    rect = None

    def on_press(event):
        nonlocal rect
        rect = canvas.create_rectangle(
            event.x, event.y, event.x, event.y,
            outline='red', width=4, fill=""
        )

    def on_drag(event):
        if rect:
            x1, y1, _, _ = canvas.coords(rect)
            canvas.coords(rect, x1, y1, event.x, event.y)

    def on_release(event):
        nonlocal coords
        if rect:
            coords = canvas.coords(rect)
            overlay.destroy()  # Destroy the selection overlay
            coord_queue.put(coords)  # Put the coordinates in the queue
            root.quit()  # Exit the Tkinter mainloop

    canvas.bind("<ButtonPress-1>", on_press)
    canvas.bind("<B1-Motion>", on_drag)
    canvas.bind("<ButtonRelease-1>", on_release)

    overlay.grab_set()  # Force focus to the overlay window
    root.mainloop()

def create_outline_window(root, coords):
    """
    Creates an outline window at the specified coordinates.

    Args:
        root (tk.Tk): The root Tkinter instance.
        coords (list): The coordinates of the selected region [x1, y1, x2, y2].
    """
    x1, y1, x2, y2 = map(int, coords)
    width = abs(x2 - x1)
    height = abs(y2 - y1)
    x = min(x1, x2)
    y = min(y1, y2)

    # Create outline window (transparent background)
    outline_window = tk.Toplevel(root)
    outline_window.geometry(f"{width}x{height}+{x}+{y}")
    outline_window.overrideredirect(True)  # Remove window decorations (borderless)
    outline_window.attributes('-topmost', True)  # Keep window on top
    outline_window.attributes('-transparentcolor', outline_window['bg'])  # Make the background fully transparent

    outline_canvas = tk.Canvas(outline_window, bd=0, highlightthickness=0)
    outline_canvas.pack(fill=tk.BOTH, expand=True)

    # Draw the red outline
    outline_canvas.create_rectangle(
        0, 0, width, height,
        outline='red', width=4, fill=""
    )

    # Add a button with no frame, background, or extra border
    close_btn = tk.Button(
        outline_window,
        text="Close",
        command=outline_window.destroy,
        bg='white',
        fg='black',
        font=('Helvetica', 12, 'bold'),
        relief='flat',  # No border
        highlightthickness=0
    )
    close_btn.place(relx=0.5, rely=0.5, anchor='center')  # Center the button inside the outline

def start_selection(coord_queue):
    """
    Starts the region selection process in a separate thread.

    Args:
        coord_queue (queue.Queue): A queue to store the selected coordinates.
    """
    selection_thread = threading.Thread(
        target=select_area,
        args=(coord_queue,)
    )
    selection_thread.daemon = True  # Ensure the thread exits when the main program exits
    selection_thread.start()

# Example usage
if __name__ == "__main__":
    # Create a queue to store the selected coordinates
    coord_queue = queue.Queue()

    # Start the selection process
    start_selection(coord_queue)

    # Initialize the main Tkinter root
    root = tk.Tk()
    root.withdraw()  # Hide the root window

    # Wait for the coordinates to be selected
    coords = coord_queue.get()

    # Create the outline window
    create_outline_window(root, coords)

    # Run the Tkinter mainloop
    root.mainloop()
    print(f"Selected coordinates: {coords}")
