import subprocess
import time
import os
import urllib.request
from curl_cffi import requests

# We will read the first proxy from proxies.txt to really test it
proxy_str = ""
with open("proxies.txt") as f:
    for line in f:
        if "ss," in line:
            proxy_str = line.strip()
            break

parts = proxy_str.split("=", 1)
name = parts[0].strip()
cfg = parts[1].strip().split(",")
host = cfg[1].strip()
port = cfg[2].strip()
params = {}
for p in cfg[3:]:
    if "=" in p:
        k, v = p.split("=", 1)
        params[k.strip()] = v.strip()

method = params.get("encrypt-method", "")
password = params.get("password", "")
obfs = params.get("obfs", "")
obfs_host = params.get("obfs-host", "")

def test_mihomo(use_en0):
    port_local = 11111 if use_en0 else 11112
    interface_cfg = "\n    interface-name: en0" if use_en0 else ""
    plugin_cfg = f"""
    plugin: obfs
    plugin-opts:
      mode: {obfs}
      host: {obfs_host}
""" if obfs else ""

    yaml_cfg = f"""
mode: global
mixed-port: {port_local}
bind-address: '127.0.0.1'
dns:
  enable: true
  nameserver:
    - 223.5.5.5
proxies:
  - name: "test_proxy"
    type: ss
    server: "{host}"
    port: {port}
    cipher: "{method}"
    password: "{password}"{interface_cfg}{plugin_cfg}
"""
    with open(f"test_cfg_{port_local}.yaml", "w") as f: f.write(yaml_cfg)
    proc = subprocess.Popen(["./.venv/bin/mihomo", "-f", f"test_cfg_{port_local}.yaml"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    time.sleep(2)
    try:
        prox = {"http": f"socks5://127.0.0.1:{port_local}", "https": f"socks5://127.0.0.1:{port_local}"}
        resp = requests.get("http://httpbin.org/ip", proxies=prox, impersonate="chrome", timeout=5)
        return resp.json()["origin"]
    except Exception as e:
        return f"Error: {e}"
    finally:
        proc.terminate()
        proc.wait(timeout=2)
        os.remove(f"test_cfg_{port_local}.yaml")

print("Without en0:", test_mihomo(False))
print("With en0:", test_mihomo(True))
