import json
import os
from .constant import cdn_file, domains
from .globalping.execute import get_cdn


def update_cdn_info():
    old_cdn_ips = []
    if os.path.exists(cdn_file) and os.path.getsize(cdn_file) > 0:
        try:
            with open(cdn_file, "r") as f:
                old_cdn_ips = json.load(f)
        except Exception:
            old_cdn_ips = []

    cdn_ips = get_cdn(domains, force=True)
    if not cdn_ips and old_cdn_ips:
        print(
            f"\nCDN refresh returned no IPs, keep existing cache. Total CDN IPs: {len(old_cdn_ips)}"
        )
        return old_cdn_ips

    with open(cdn_file, "w") as f:
        json.dump(cdn_ips, f)
    print(f"\nCDN information updated. Total CDN IPs: {len(cdn_ips)}")
    return cdn_ips


def load_cdn_info():
    if not os.path.exists(cdn_file) or os.path.getsize(cdn_file) == 0:
        return update_cdn_info()
    with open(cdn_file, "r") as f:
        cdn_ips = json.load(f)
    return cdn_ips
