import json
import os
import requests
from urllib.parse import urlparse

def download_file(url, directory):
    response = requests.get(url)
    if response.status_code == 200:
        filename = os.path.basename(urlparse(url).path)
        filepath = os.path.join(directory, filename)
        with open(filepath, 'wb') as f:
            f.write(response.content)
        print(f"Downloaded: {filename}")
    else:
        print(f"Failed to download: {url}")

# Read the JSON file
with open('singbox_rule_set.json', 'r') as f:
    data = json.load(f)

# Create the ruleset directory if it doesn't exist
os.makedirs('./ruleset', exist_ok=True)

# Extract URLs and download files
for rule_set in data['route']['rule_set']:
    url = rule_set['url']
    download_file(url, './ruleset')

print("Download complete.")