#!/usr/bin/env python3
import requests
import json

# -------- 配置部分 --------
API_URL = "http://127.0.0.1:9097"  # Clash 本地 API
API_KEY = "esZnx8"                 # Clash API 密钥
GROUP_NAME = "♻️ 手动切换"               # 要轮换的策略组名称
# ---------------------------

headers = {
    "Authorization": f"Bearer {API_KEY}",
    "Content-Type": "application/json"
}

def get_proxies():
    """获取策略组和节点信息"""
    resp = requests.get(f"{API_URL}/proxies", headers=headers, timeout=5)
    resp.raise_for_status()
    return resp.json()

def switch_next_node():
    proxies = get_proxies().get('proxies')
    
    if GROUP_NAME not in proxies:
        print(f"策略组 '{GROUP_NAME}' 不存在")
        return
    
    group = proxies[GROUP_NAME]
    all_nodes = group['all']
    current_node = group['now']
    
    # 找到下一个节点
    try:
        idx = all_nodes.index(current_node)
        next_idx = (idx + 1) % len(all_nodes)
        next_node = all_nodes[next_idx]
    except ValueError:
        # 当前节点不在列表里，选择第一个
        next_node = all_nodes[0]
    
    # 切换节点（注意 API 路径修改）
    data = {"name": next_node}
    resp = requests.put(f"{API_URL}/proxies/{GROUP_NAME}", headers=headers, json=data, timeout=5)
    resp.raise_for_status()
    
    print(f"[OK] 策略组 '{GROUP_NAME}' 切换完成")
    print(f"    当前节点: {current_node} → {next_node}")
    return next_node

if __name__ == "__main__":
    switch_next_node()