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

yaml_config = """
mode: rule
mixed-port: 10899
bind-address: '127.0.0.1'
proxies:
"""
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)
cfg = parts[1].strip().split(",")
params = dict(p.strip().split("=", 1) for p in cfg[3:] if "=" in p)
yaml_config += f"""  - name: "test"
    type: ss
    server: "{cfg[1].strip()}"
    port: {cfg[2].strip()}
    cipher: "{params.get('encrypt-method', '')}"
    password: "{params.get('password', '')}"
"""
if "obfs" in params:
    yaml_config += f"    plugin: obfs\n    plugin-opts:\n      mode: {params['obfs']}\n      host: {params['obfs-host']}\n"

yaml_config += """
proxy-groups:
  - name: "Proxy"
    type: select
    proxies:
      - "test"
rules:
  - MATCH, Proxy
"""
with open("test_503.yaml", "w") as f: f.write(yaml_config)

proc = subprocess.Popen(["./.venv/bin/mihomo", "-f", "test_503.yaml"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
time.sleep(2)

s = requests.Session()
p = {"http": "socks5://127.0.0.1:10899", "https": "socks5://127.0.0.1:10899"}
try:
    ip_resp = s.get("http://httpbin.org/ip", proxies=p, impersonate="chrome", timeout=5)
    print("Proxy IP:", ip_resp.json()["origin"])
    
    r1 = s.get("https://zlib.li/", proxies=p, impersonate="chrome", timeout=10)
    print("Index status:", r1.status_code)
finally:
    proc.terminate()
