#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
import subprocess
import time
import os
import xbmc
import xbmcgui

def reboot_system():
    """先同步数据再强制重启"""
    xbmc.log("同步数据并强制重启", xbmc.LOGINFO)
    try:
        subprocess.run(["sync"], timeout=2, check=True)
    except subprocess.TimeoutExpired:
        xbmc.log("数据同步同步超时，继续执行重启", xbmc.LOGWARNING)
    subprocess.run(["reboot", "-f"])

def poweroff_system():
    """完全按正常流程关机，显示输出延后1秒关闭，不强制终止任何插件"""
    xbmc.log("同步数据并执行KODI安全关机", xbmc.LOGINFO)
    
    # 1. 同步数据（限制2秒超时）
    try:
        subprocess.run(["sync"], timeout=2, check=True)
    except subprocess.TimeoutExpired:
        xbmc.log("数据同步超时，继续执行关机", xbmc.LOGWARNING)

    # 2. 显示通知（1.5秒）
    xbmcgui.Dialog().notification(
        "系统提示", 
        "正在关机...",
        xbmcgui.NOTIFICATION_INFO, 
        1500
    )

    # 3. 延后1秒关闭显示输出
    time.sleep(1)  # 延后1秒执行关闭显示
    try:
        display_path = "/sys/class/graphics/fb0/blank"
        if os.path.exists(display_path) and os.access(display_path, os.W_OK):
            with open(display_path, 'w') as f:
                f.write("1\n")
            xbmc.log(f"已通过 {display_path} 关闭视频输出", xbmc.LOGINFO)
    except Exception as e:
        xbmc.log(f"关闭视频输出失败: {str(e)}", xbmc.LOGERROR)

    # 4. 短暂等待后执行正常关机
    time.sleep(0.2)
    xbmc.executebuiltin("Powerdown()")  # 完全依赖KODI正常关机流程

if __name__ == "__main__":
    args = sys.argv[1:]
    if args and args[0].lower() == "reboot":
        reboot_system()
    elif args and args[0].lower() == "turnoff":
        poweroff_system()
    else:
        xbmc.log("未指定或参数错误，不执行任何操作。", xbmc.LOGWARNING)