import xbmc
import time
import re
import os

def get_pretty_name_from_os_release():
    """从/etc/os-release文件中获取PRETTY_NAME的值"""
    xbmc.log("尝试从/etc/os-release获取PRETTY_NAME", xbmc.LOGINFO)
    os_release_path = "/etc/os-release"
    pretty_name = None

    # 检查文件是否存在
    if not os.path.exists(os_release_path):
        xbmc.log(f"{os_release_path} 文件不存在", xbmc.LOGWARNING)
        return None

    try:
        with open(os_release_path, 'r', encoding='utf-8') as f:
            for line in f:
                # 匹配以PRETTY_NAME=开头的行，并捕获双引号内的内容
                match = re.match(r'^PRETTY_NAME="(.*)"', line.strip())
                if match:
                    pretty_name = match.group(1)
                    break
    except Exception as e:
        xbmc.log(f"读取或解析 {os_release_path} 失败: {e}", xbmc.LOGERROR)
        return None

    if pretty_name:
        xbmc.log(f"成功获取PRETTY_NAME: {pretty_name}", xbmc.LOGINFO)
        return pretty_name
    else:
        xbmc.log(f"在 {os_release_path} 中未找到PRETTY_NAME字段", xbmc.LOGWARNING)
        return None

def extract_date(version_string):
    """从版本字符串中提取日期"""
    if not version_string:
        return None

    # 正则匹配8位数字的日期（YYYYMMDD格式）
    pattern = re.compile(r'(\d{8})')
    match = pattern.search(version_string)

    if match:
        date_str = match.group(1)
        xbmc.log(f"提取到的构建日期: {date_str}", xbmc.LOGINFO)
        return date_str
    else:
        xbmc.log(f"无法从'{version_string}'中提取日期", xbmc.LOGWARNING)
        return None

def get_prefix_from_version_string(version_string):
    """根据版本字符串判断前缀"""
    if not version_string:
        return "未知"

    lower_version = version_string.lower()

    # 优先判断社区/CPM版本
    if "community" in lower_version or "cpm" in lower_version:
        return "CPM分支-"
    elif "nightly" in lower_version:
        return "夜版CE-"
    elif "official" in lower_version and "nightly" not in lower_version:
        return "原版CE-"
    else:
        return "未知-"

def set_build_date_with_prefix():
    """根据版本字符串判断前缀，并设置构建日期"""
    # 从/etc/os-release获取版本字符串
    version_string = get_pretty_name_from_os_release()
    xbmc.log(f"获取到的版本字符串: {version_string}", xbmc.LOGINFO)

    # 从版本字符串中提取日期
    build_date = extract_date(version_string)

    xbmc.log(f"处理后的构建日期: {build_date}", xbmc.LOGINFO)

    if not build_date:
        final_build_date = "未知"  # 无法获取日期时设置为中文"未知"
    else:
        # 获取日期成功后再获取前缀
        prefix = get_prefix_from_version_string(version_string)
        final_build_date = f"{prefix}{build_date}"

    xbmc.log(f"设置Skin.SetString(BuildDate, {final_build_date})", xbmc.LOGINFO)
    xbmc.executebuiltin(f'Skin.SetString(BuildDate,{final_build_date})')

def set_version_from_file():
    """从version.txt读取版本号，如果不存在则根据条件创建"""
    from xbmcvfs import translatePath, exists
    import subprocess

    home_path = translatePath('special://home/userdata/')
    version_file = os.path.join(home_path, 'version.txt')

    # 如果version.txt已存在，则直接读取
    if exists(version_file):
        try:
            with open(version_file, 'r', encoding='utf-8', errors='ignore') as f:
                version_content = f.readline().strip()
            xbmc.executebuiltin(f'Skin.SetString(version,{version_content})')
            return
        except Exception as e:
            xbmc.log(f"读取version.txt失败: {str(e)}", xbmc.LOGERROR)
            # 即使读取失败，我们也继续尝试创建新文件

    # 检查挂载到 /flash 的分区大小
    try:
        # 使用df命令获取 /flash 分区大小信息
        result = subprocess.check_output(['df', '-P', '/flash'],
                                         stderr=subprocess.STDOUT,
                                         universal_newlines=True)

        # 解析输出获取分区大小(KB)
        lines = result.strip().split('\n')
        if len(lines) >= 2:
            parts = lines[1].split()
            if len(parts) >= 2:
                size_kb = int(parts[1])
                size_mb = size_kb / 1024

                xbmc.log(f"/flash分区大小: {size_mb:.2f}MB", xbmc.LOGINFO)

                # 判断分区大小是否大于800MB
                if size_mb > 800:
                    version_content = "Minsk-20251007"
                else:
                    # 检查/flash目录下的文件
                    if exists('/flash/KERNELcpm.img.md5') or exists('/flash/KERNELce.img.md5'):
                        version_content = "Minsk-20250926"
                    else:
                        version_content = "Minsk-早期版本"

                # 创建version.txt文件
                with open(version_file, 'w', encoding='utf-8') as f:
                    f.write(version_content)

                xbmc.log(f"创建version.txt，内容: {version_content}", xbmc.LOGINFO)
                xbmc.executebuiltin(f'Skin.SetString(version,{version_content})')
                return

    except Exception as e:
        xbmc.log(f"检查/flash分区大小失败: {str(e)}", xbmc.LOGERROR)

    # 如果所有检查都失败，设置为"Minsk-未知版本"
    xbmc.executebuiltin('Skin.SetString(version,Minsk-未知版本)')

if __name__ == '__main__':
    xbmc.log("开始执行版本信息脚本", xbmc.LOGINFO)
    set_build_date_with_prefix()
    set_version_from_file()
    xbmc.log("版本信息脚本执行完成", xbmc.LOGINFO)