#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""键盘快捷键模块"""

import tkinter as tk
from tkinter import messagebox

from app.ui.ui_widgets import center_window
from app.ui.action_handlers import (
    process_single_image_with_status,
    process_excel_file_with_status,
    batch_ocr_with_status,
    run_pipeline_directly,
    merge_orders_with_status,
)
from app.ui.file_operations import clean_cache


def bind_keyboard_shortcuts(root, log_widget, status_bar):
    """绑定键盘快捷键"""
    root.bind('<Control-o>', lambda e: process_single_image_with_status(log_widget, status_bar))
    root.bind('<Control-e>', lambda e: process_excel_file_with_status(log_widget, status_bar))
    root.bind('<Control-b>', lambda e: batch_ocr_with_status(log_widget, status_bar))
    root.bind('<Control-p>', lambda e: run_pipeline_directly(log_widget, status_bar))
    root.bind('<Control-m>', lambda e: merge_orders_with_status(log_widget, status_bar))
    root.bind('<F5>', lambda e: clean_cache(log_widget))
    root.bind('<Escape>', lambda e: root.quit() if messagebox.askyesno("确认退出", "确定要退出程序吗？") else None)
    root.bind('<F1>', lambda e: show_shortcuts_help())


def show_shortcuts_help():
    """显示快捷键帮助对话框"""
    help_dialog = tk.Toplevel()
    help_dialog.title("快捷键帮助")
    help_dialog.geometry("400x450")
    center_window(help_dialog)

    tk.Label(help_dialog, text="键盘快捷键", font=("Arial", 16, "bold")).pack(pady=10)

    help_text = tk.Text(help_dialog, wrap=tk.WORD, width=50, height=20)
    help_text.pack(padx=20, pady=10, fill=tk.BOTH, expand=True)

    shortcuts = """
    Ctrl+O: 处理单个图片
    Ctrl+E: 处理Excel文件
    Ctrl+B: OCR批量识别
    Ctrl+P: 完整处理流程
    Ctrl+M: 合并采购单
    F5: 清除处理缓存
    Esc: 退出程序
    """

    help_text.insert(tk.END, shortcuts)
    help_text.configure(state=tk.DISABLED)

    tk.Button(help_dialog, text="确定", command=help_dialog.destroy).pack(pady=10)

    help_dialog.lift()
    help_dialog.attributes('-topmost', True)
    help_dialog.after_idle(lambda: help_dialog.attributes('-topmost', False))
