import sys
import tkinter as tk
from tkinter import ttk


class LogViewer:
    """Tkinter dialog for viewing tooltray log file."""

    def __init__(self, log_path: str) -> None:
        self.log_path = log_path

        self.root = tk.Tk()
        self.root.title("Tool Tray Logs")
        self.root.resizable(True, True)
        self.root.minsize(500, 400)

        # Center window on screen
        window_width = 700
        window_height = 500
        screen_width = self.root.winfo_screenwidth()
        screen_height = self.root.winfo_screenheight()
        x = (screen_width - window_width) // 2
        y = (screen_height - window_height) // 2
        self.root.geometry(f"{window_width}x{window_height}+{x}+{y}")

        # Main frame
        frame = ttk.Frame(self.root, padding=10)
        frame.pack(fill=tk.BOTH, expand=True)

        # Log text widget with scrollbar
        log_frame = ttk.Frame(frame)
        log_frame.pack(fill=tk.BOTH, expand=True)

        self.log_text = tk.Text(
            log_frame,
            wrap=tk.NONE,
            font=("Monaco", 10) if sys.platform == "darwin" else ("Consolas", 9),
            state=tk.DISABLED,
            background="#1e1e1e",
            foreground="#d4d4d4",
            insertbackground="#d4d4d4",
        )

        # Vertical scrollbar
        v_scrollbar = ttk.Scrollbar(
            log_frame, orient=tk.VERTICAL, command=self.log_text.yview
        )
        self.log_text.configure(yscrollcommand=v_scrollbar.set)

        # Horizontal scrollbar
        h_scrollbar = ttk.Scrollbar(
            frame, orient=tk.HORIZONTAL, command=self.log_text.xview
        )
        self.log_text.configure(xscrollcommand=h_scrollbar.set)

        # Pack widgets
        v_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        self.log_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        h_scrollbar.pack(fill=tk.X)

        # Button frame
        btn_frame = ttk.Frame(frame)
        btn_frame.pack(fill=tk.X, pady=(10, 0))

        self.copy_btn = ttk.Button(btn_frame, text="Copy All", command=self._on_copy)
        self.copy_btn.pack(side=tk.LEFT)

        ttk.Button(btn_frame, text="Refresh", command=self._load_logs).pack(
            side=tk.LEFT, padx=(5, 0)
        )

        ttk.Button(btn_frame, text="Close", command=self.root.destroy).pack(
            side=tk.RIGHT
        )

        # Path label
        path_label = ttk.Label(frame, text=f"Log file: {log_path}", foreground="gray")
        path_label.pack(anchor=tk.W, pady=(5, 0))

        # Handle Escape key
        self.root.bind("<Escape>", lambda e: self.root.destroy())

        # Load initial content
        self._load_logs()

    def _load_logs(self) -> None:
        """Load log content from file."""
        from pathlib import Path

        self.log_text.configure(state=tk.NORMAL)
        self.log_text.delete("1.0", tk.END)

        log_file = Path(self.log_path)
        if log_file.exists():
            content = log_file.read_text()
            self.log_text.insert(tk.END, content)
            # Scroll to end
            self.log_text.see(tk.END)
        else:
            self.log_text.insert(tk.END, f"Log file not found: {self.log_path}")

        self.log_text.configure(state=tk.DISABLED)

    def _on_copy(self) -> None:
        """Copy log contents to clipboard."""
        log_content = self.log_text.get("1.0", tk.END).strip()
        self.root.clipboard_clear()
        self.root.clipboard_append(log_content)

        # Brief visual feedback
        original_text = self.copy_btn.cget("text")
        self.copy_btn.config(text="Copied!")
        self.root.after(1000, lambda: self.copy_btn.config(text=original_text))

    def run(self) -> None:
        """Show the dialog."""
        self.root.mainloop()


def show_log_viewer() -> None:
    """Show log viewer dialog."""
    from tool_tray.logging import get_log_dir

    log_path = get_log_dir() / "tooltray.log"
    viewer = LogViewer(str(log_path))
    viewer.run()


def main() -> None:
    """CLI entry point for subprocess invocation."""
    show_log_viewer()


if __name__ == "__main__":
    main()
