import subprocess

def set_timezone(timezone: str) -> int:
    """使用 timedatectl 设置系统时区"""
    try:
        ret = subprocess.run(
            ["timedatectl", "set-timezone", timezone],
            check=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True
        )
        return 0
    except subprocess.CalledProcessError as e:
        print("设置时区失败:", e.stderr)
        return -1


def set_system_time(year, month, day, hour, minute, second=0) -> int:
    """使用 timedatectl 设置系统时间"""
    time_str = f"{year}-{month:02d}-{day:02d} {hour:02d}:{minute:02d}:{second:02d}"
    try:
        ret = subprocess.run(
            ["timedatectl", "set-time", time_str],
            check=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True
        )
        return 0
    except subprocess.CalledProcessError as e:
        print("设置时间失败:", e.stderr)
        return -1

def update_system_datetime(timezone, year, month, day, hour, minute, second=0):
    # 先设置时区
    if set_timezone(timezone) != 0:
        return -1

    # 再设置时间
    if set_system_time(year, month, day, hour, minute, second) != 0:
        return -2

    return 0