""" TEST_CONFIG
{
    "name": "base_deny_test",
    "network": {
        "allowInternet": false,
        "allowLocalNetwork": false,
        "allowListen": [9990],
        "allowList": ["111.63.65.247:80"]
    }
}
"""
import os, sys, json, socket, platform

def run_test():
    is_darwin = platform.system().lower() == "darwin"
    
    results = {
        "listen_9990_ok": False,
        "listen_9991_denied": False,
        "whitelist_ip_port_ok": False,
        "whitelist_ip_wrong_port_denied": False,
        "wrong_ip_denied": True # Mac 默认设为 True，跳过检查
    }

    # 1. 监听对比测试
    # 9990 (Allowed)
    try:
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            s.bind(('0.0.0.0', 9990))
            results["listen_9990_ok"] = True
    except: pass
    
    # 9991 (Denied)
    try:
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            s.bind(('0.0.0.0', 9991))
    except:
        results["listen_9991_denied"] = True

    # 2. 网络访问对比测试
    # 111.63.65.247:80 (Allowed)
    try:
        with socket.create_connection(("111.63.65.247", 80), timeout=1):
            results["whitelist_ip_port_ok"] = True
    except: pass

    # 111.63.65.247:443 (Wrong Port - Denied)
    try:
        with socket.create_connection(("111.63.65.247", 443), timeout=1):
            pass
    except:
        results["whitelist_ip_wrong_port_denied"] = True

    # 3. 跨 IP 拦截测试 (仅 Linux)
    if not is_darwin:
        results["wrong_ip_denied"] = False
        try:
            # 61.135.164.50:80 不在白名单
            with socket.create_connection(("61.135.164.50", 80), timeout=1):
                pass
        except:
            results["wrong_ip_denied"] = True

    test_success = all(results.values())
    print(json.dumps({"testSuccess": test_success, "details": results}, indent=2))

if __name__ == "__main__":
    run_test()