# -*- coding: utf-8 -*-
import os
import json
import datetime
import logging
from pathlib import Path

# 配置文件路径
UPDATE_RATE_CONFIG = Path("/var/cache/kylin-system-updater/rate_limits.json")
P2P_RATE_CONFIG = Path("/var/cache/apt-p2p/p2p_rate_limits.json")

# ----------------- 内部私有方法 -----------------

def _load_config_file(file_path):
    """安全读取 JSON 配置文件，文件不存在或内容无效返回空字典"""
    with open(file_path, "r") as f:
        return json.load(f)


def _normalize_rate(rate):
    """确保速率为数字字符串，否则返回 '0'"""
    rate_str = str(rate).strip()
    return rate_str if rate_str.isdigit() else "0"


def _get_rate_from_schedule(rate_limits, current_time):
    """
    根据分时策略(rate_limits)和当前时间(current_time)获取限速
    返回 (download_rate, upload_rate) 或 (None, None) 表示未匹配
    """
    for limit in rate_limits:
        if not isinstance(limit, dict):
            continue
        time_period = limit.get("time_period", "")
        if time_period != "daily":
            continue
        start_time_str = limit.get("start_time")
        end_time_str = limit.get("end_time")
        if not start_time_str or not end_time_str:
            continue
        start_time = datetime.datetime.strptime(start_time_str, "%H:%M").time()
        end_time = datetime.datetime.strptime(end_time_str, "%H:%M").time()
        if start_time <= current_time <= end_time:
            download_rate = _normalize_rate(limit.get("download_limit", 0))
            upload_rate = _normalize_rate(limit.get("upload_limit", 0))
            return download_rate, upload_rate
    return None, None


# ----------------- 公共方法 -----------------

def calculate_current_rate(params):
    """
    根据配置计算当前下载和上传限速
    返回 (download_rate, p2p_upload_rate) 都为字符串类型
    """
    current_time = datetime.datetime.now().time()

    download_rate, upload_rate = None, None

    if params.get("policy_limits"):
        rate_limits = params.get("rate_limits", [])
        download_rate, upload_rate = _get_rate_from_schedule(rate_limits, current_time)

    if download_rate is None:
        download_rate = _normalize_rate(params.get("global_download_limit", params.get("default_download", 0)))
    if upload_rate is None:
        upload_rate = _normalize_rate(params.get("default_upload", 0))

    return download_rate, upload_rate


def get_download_limit() -> int:
    """获取系统更新的当前限速"""
    try:
        if not UPDATE_RATE_CONFIG.exists():
            return 0

        config = _load_config_file(UPDATE_RATE_CONFIG)
        download_rate, _ = calculate_current_rate(config)

        return int(download_rate)
    except Exception as e:
        logging.warning("Error getting download limit: %s", e)
        return 0

def get_p2p_rate_limit():
    """获取 P2P 下载/上传的当前限速"""
    config = _load_config_file(P2P_RATE_CONFIG)
    return calculate_current_rate(config)


def write_config_file(file_path, data):
    """通用保存 JSON 配置"""
    file_path = Path(file_path)
    file_path.parent.mkdir(parents=True, exist_ok=True)
    with open(file_path, "w") as f:
        json.dump(data, f, indent=4)


def set_update_rate_limit(data):
    """设置系统更新限速配置"""
    write_config_file(UPDATE_RATE_CONFIG, data)


def set_p2p_rate_limit(data):
    """设置 P2P 限速配置"""
    write_config_file(P2P_RATE_CONFIG, data)
