import sqlite3, json, zipfile, os, subprocess, time

db_bytes = open("/tmp/guiNDB.db", "rb").read()
rules_bytes = open("/tmp/Iran-Direct-Rules.json", "rb").read()
rules = json.loads(rules_bytes.decode())

# 1. Update /tmp/v2rayN-7.25.6-xray.zip
src_zip = "/tmp/v2rayN-7.25.6-xray.zip"
tmp_zip = "/tmp/v2rayN-7.25.6-xray.new.zip"
with zipfile.ZipFile(src_zip, "r") as zin, zipfile.ZipFile(tmp_zip, "w", zipfile.ZIP_DEFLATED) as zout:
    for item in zin.infolist():
        if item.filename not in ("guiConfigs/guiNDB.db", "Iran-Direct-Rules.json"):
            zout.writestr(item, zin.read(item.filename))
    zout.writestr("guiConfigs/guiNDB.db", db_bytes)
    zout.writestr("Iran-Direct-Rules.json", rules_bytes)
os.replace(tmp_zip, src_zip)
print("Updated /tmp/v2rayN-7.25.6-xray.zip:", os.path.getsize(src_zip))

# 2. Update 3x-ui subJsonRules & subRoutingRules with full RIPE Iran CIDRs + Iranian domains
xui_rules = json.dumps([
    {
        "type": "field",
        "outboundTag": "direct",
        "domain": rules[0]["Domain"]
    },
    {
        "type": "field",
        "outboundTag": "direct",
        "ip": rules[1]["Ip"]
    }
])
conn = sqlite3.connect("/etc/x-ui/x-ui.db")
for k in ("subJsonRules", "subRoutingRules"):
    conn.execute("UPDATE settings SET value=? WHERE key=?", (xui_rules, k))
conn.commit()
conn.close()

# 3. Test live with /usr/local/x-ui/bin/xray-linux-amd64
os.makedirs("/tmp/xray-verify", exist_ok=True)
for gf in ("geoip.dat", "geosite.dat"):
    if os.path.exists(f"/usr/local/x-ui/bin/{gf}"):
        subprocess.run(["cp", "-f", f"/usr/local/x-ui/bin/{gf}", f"/tmp/xray-verify/{gf}"])

test_cfg = {
    "log": {
        "loglevel": "debug",
        "error": "/tmp/xray-verify/error.log"
    },
    "inbounds": [
        {
            "tag": "socks",
            "port": 20808,
            "listen": "127.0.0.1",
            "protocol": "socks",
            "sniffing": {"enabled": True, "destOverride": ["http", "tls"]},
            "settings": {"auth": "noauth", "udp": True}
        }
    ],
    "outbounds": [
        {
            "tag": "proxy",
            "protocol": "vless",
            "settings": {
                "vnext": [{
                    "address": "46.8.236.174",
                    "port": 443,
                    "users": [{
                        "id": "30203e88-8c87-4f7b-b37a-1a4a4426789c",
                        "encryption": "none",
                        "flow": "xtls-rprx-vision"
                    }]
                }]
            },
            "streamSettings": {
                "network": "tcp",
                "security": "reality",
                "realitySettings": {
                    "serverName": "www.microsoft.com",
                    "fingerprint": "chrome",
                    "show": False,
                    "publicKey": "aTK1wQR3WLErxAczHdjg537YDQcBfCZzB8LmkrjnIDo",
                    "shortId": "6ba85179e30d4fc2",
                    "spiderX": "/"
                }
            }
        },
        {
            "tag": "direct",
            "protocol": "freedom",
            "settings": {}
        }
    ],
    "routing": {
        "domainStrategy": "IPIfNonMatch",
        "rules": [
            {
                "type": "field",
                "outboundTag": "direct",
                "domain": rules[0]["Domain"]
            },
            {
                "type": "field",
                "outboundTag": "direct",
                "ip": rules[1]["Ip"]
            },
            {
                "type": "field",
                "port": "0-65535",
                "outboundTag": "proxy"
            }
        ]
    }
}
json.dump(test_cfg, open("/tmp/xray-verify/config.json", "w"), indent=2)
if os.path.exists("/tmp/xray-verify/error.log"):
    os.remove("/tmp/xray-verify/error.log")

proc = subprocess.Popen(["/usr/local/x-ui/bin/xray-linux-amd64", "run", "-c", "/tmp/xray-verify/config.json"], cwd="/tmp/xray-verify")
time.sleep(1.5)

tests = [
    ("International (ifconfig.me)", "https://ifconfig.me/ip"),
    ("Iran Domain (tabdeal.org)", "https://tabdeal.org"),
    ("Iran .ir Domain (arvancloud.ir)", "https://www.arvancloud.ir"),
    ("Iran Official CIDR IP (185.143.233.5)", "https://185.143.233.5"),
    ("Iran Official CIDR IP (5.119.209.23)", "https://5.119.209.23")
]

for label, url in tests:
    r = subprocess.run(["curl", "-sk", "-x", "socks5h://127.0.0.1:20808", "--max-time", "4", "-o", "/dev/null", "-w", "HTTP=%{http_code}", url], capture_output=True, text=True)
    print(f"TEST {label}: {r.stdout.strip()}")

proc.terminate()
time.sleep(0.5)

print("=== XRAY ROUTING DECISIONS ===")
for line in open("/tmp/xray-verify/error.log").read().splitlines():
    if "taking detour" in line:
        print(line)
