import logging
import sys
import os
from pathlib import Path

# 统一配置 lawspeed.* 日志（所有 service 模块共用）
_log = logging.getLogger("lawspeed")
if not _log.handlers:
    _h = logging.StreamHandler(sys.stderr)
    _h.setFormatter(logging.Formatter(
        fmt="%(asctime)s [%(levelname)s] %(name)s - %(message)s",
        datefmt="%H:%M:%S",
    ))
    _log.addHandler(_h)
    _log.setLevel(logging.DEBUG)

import webview
from conf import SecureConfigDB, DEBUG
from api.window_controller import WindowController
from api.main_api import MainApi

localization = {
        'global.cancel': '取消',
        'global.saveFile': '保存文件',
        'cocoa.menu.about': '关于程序',
        'cocoa.menu.services': '服务',
        'cocoa.menu.view': '查看',
        'cocoa.menu.hide': '隐藏',
        'cocoa.menu.edit': '编辑',
        'cocoa.menu.hideOthers': '隐藏其他',
        'cocoa.menu.showAll': '显示所有',
        'cocoa.menu.quit': '退出',
        'cocoa.menu.fullscreen': '全屏切换',
        'windows.fileFilter.allFiles': '所有文件',
        'windows.fileFilter.otherFiles': '其他文件',
        'linux.openFile': '打开文件',
        'linux.openFiles': '打开多个文件',
        'linux.openFolder': '打开文件夹',
    }


if __name__ == "__main__":
    with SecureConfigDB() as conf:
        if not conf.get_config('download_path'):
            conf.set_config('download_path', str(Path.home() / 'Downloads'))

    controller = WindowController()
    api = MainApi(controller)

    def create_main_window():
        window = webview.create_window(
            title="简弈诉达文书下载",
            url="frontend/dist/index.html",
            js_api=api,  # 直接暴露MainApi实例
            width=1200,
            height=800
        )
        
        # 注入窗口引用
        controller.set_main_window(window)
        api.window = window.title  # 设置API的窗口引用

        # 绑定关闭事件
        window.events.closed += controller.destroy_children

        return window
    
    create_main_window()
    # 启动应用
    webview.start(
        debug=DEBUG,
        menu=[],
        localization=localization
    )
