import requests
from datetime import datetime, timezone

# --- 配置部分 ---
API_URL = 'https://api.text.skin/api/proxy/create'
BEARER_TOKEN = 'tok_e946329a60ff45ba807f3f41b0e8b7fc'    # 替换为你的真实 Token
FILE_PATH = 'proxylist.txt'   # 替换为你实际的文本文件名 (例如 proxies.txt)

headers = {
    'accept': 'application/json',
    'Authorization': f'Bearer {BEARER_TOKEN}',
    'Content-Type': 'application/json'
}

def main():
    proxies = []
    
    # 1. 逐行读取文本文件
    try:
        with open(FILE_PATH, 'r', encoding='utf-8') as f:
            for line in f:
                line = line.strip()
                if not line:
                    continue  # 跳过空行
                
                # 按冒号分割: IP/域名:端口:账号:密码
                # 使用 split(':', 3) 防止密码中碰巧包含冒号导致分割错误
                parts = line.split(':', 3) 
                
                if len(parts) == 4:
                    proxies.append({
                        "ip": parts[0],
                        "port": int(parts[1]),  # 端口需转为数字
                        "username": parts[2],
                        "password": parts[3]
                    })
                else:
                    print(f"警告: 格式不符合预期(应为 IP:端口:用户名:密码)，已跳过该行 -> {line}")
                    
    except FileNotFoundError:
        print(f"错误: 找不到文件 {FILE_PATH}")
        return

    if not proxies:
        print("没有读取到任何有效的代理，请检查文件格式。")
        return

    print(f"共读取到 {len(proxies)} 个代理，准备开始上传...\n")

    # 2. 遍历列表并发送请求
    success_count = 0
    fail_count = 0

    for index, proxy in enumerate(proxies, start=1):
        # 组装 API Payload
        payload = {
            "pool_name": "proxy-cheap",  # 自定义你的代理池名称
            "proto": "http",          # 文本中没有协议字段，默认为 http。如果是 socks5 请自行修改
            "ip": proxy["ip"],
            "port": proxy["port"],
            "username": proxy["username"],
            "password": proxy["password"],
            # 设置下次使用时间（当前UTC时间）
            "next_use_time": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z",
            "status": "active"        # 默认状态
        }

        # 3. 发送 POST 请求
        try:
            response = requests.post(API_URL, headers=headers, json=payload, timeout=10)
            
            # 判断响应状态码
            if response.status_code in (200, 201):
                print(f"[{index}/{len(proxies)}] 成功: 上传 {payload['ip']}:{payload['port']}")
                success_count += 1
            else:
                print(f"[{index}/{len(proxies)}] 失败: {payload['ip']}:{payload['port']} | HTTP状态码: {response.status_code} | 详情: {response.text}")
                fail_count += 1
                
        except requests.exceptions.RequestException as e:
            print(f"[{index}/{len(proxies)}] 请求异常: {payload['ip']}:{payload['port']} | 错误: {e}")
            fail_count += 1

    # 打印最终统计
    print("\n--- 上传完成 ---")
    print(f"成功: {success_count} 条")
    print(f"失败: {fail_count} 条")

if __name__ == "__main__":
    main()