import json
import re

def convert_to_singbox(input_file, output_file):
    with open(input_file, 'r', encoding='utf-8') as f:
        lines = f.readlines()

    rule_groups = {}
    for line in lines:
        line = line.strip()
        if line.startswith('- '):
            parts = line.split(',')
            if len(parts) >= 3:
                rule_type = parts[0][2:]  # Remove '- ' from the start
                value = parts[1]
                outbound = parts[2]

                if (rule_type, outbound) not in rule_groups:
                    rule_groups[(rule_type, outbound)] = []
                rule_groups[(rule_type, outbound)].append(value)
            elif len(parts) == 2:
                rule_type = parts[0][2:]
                if rule_type == 'MATCH':
                    final_outbound = parts[1]
                    continue
    singbox_rules = []
    for (rule_type, outbound), values in rule_groups.items():
        if rule_type == 'DOMAIN-SUFFIX':
            singbox_rules.append({
                "domain_suffix": values,
                "outbound": outbound
            })
        elif rule_type == 'DOMAIN-KEYWORD':
            singbox_rules.append({
                "domain_keyword": values,
                "outbound": outbound
            })
        elif rule_type == 'DOMAIN':
            singbox_rules.append({
                "domain": values,
                "outbound": outbound
            })
        elif rule_type == 'IP-CIDR':
            singbox_rules.append({
                "ip_cidr": values,
                "outbound": outbound
            })
        elif rule_type == 'GEOIP':
            singbox_rules.append({
                "geoip": values,
                "outbound": outbound
            })

    singbox_config = {
        "route": {
            "rules": singbox_rules,
            "final": final_outbound
        }
    }

    with open(output_file, 'w', encoding='utf-8') as f:
        json.dump(singbox_config, f, indent=2, ensure_ascii=False)

# Usage
input_file = 'wget_clash_64.txt'
output_file = 'singbox_rules.json'
convert_to_singbox(input_file, output_file)