import requests
import time
import json
from urllib.parse import urlencode

class CaptchaTester:
    def __init__(self, api_key):
        self.config = {
            'capsolver_key': api_key
        }

    def _log(self, message):
        print(f"[{time.strftime('%H:%M:%S')}] {message}")

    def solve_captcha(self, page_url: str, task_type: str, site_key: str, action: str = None) -> str:
        """调用 Capsolver 获取 ReCaptcha V3 Token"""
        capsolver_key = self.config.get('capsolver_key')
        if not capsolver_key:
            raise ValueError("Capsolver API key missing")

        task = {
            "type": task_type,
            "websiteURL": page_url,
            "websiteKey": site_key,
            "pageAction": action
        }
        
        payload = {"clientKey": capsolver_key, "task": task}
        
        # 创建任务
        res = requests.post("https://api.capsolver.com/createTask", json=payload, timeout=20)
        resp_json = res.json()
        if resp_json.get("errorId") != 0:
            raise Exception(f"创建任务失败: {res.text}")

        task_id = resp_json.get("taskId")
        self._log(f"任务已创建: {task_id}. 正在等待高分 Token...")

        # 轮询结果
        for i in range(20):
            r = requests.post(
                "https://api.capsolver.com/getTaskResult", 
                json={"clientKey": capsolver_key, "taskId": task_id}, 
                timeout=20
            )
            data = r.json()
            if data.get("status") == "ready":
                self._log("验证码解决成功!")
                return data["solution"].get("gRecaptchaResponse") or data["solution"].get("token")
            
            time.sleep(3)
        raise Exception("Capsolver 任务超时")

    def test_score(self):
        # 1. 目标网站配置 (基于你提供的 curl 信息)
        test_page = "https://recaptcha-demo.appspot.com/recaptcha-v3-request-scores.php"
        # 这是该演示页面的公钥
        site_key = "6LdKlZEpAAAAAAOQjzC2v_d36tWxCl6dWsozdSy9" 
        action = "examples/v3scores"
        
        try:
            # 2. 从 Capsolver 获取 Token
            token = self.solve_captcha(
                page_url=test_page,
                task_type="ReCaptchaV3TaskProxyLess", 
                site_key=site_key,
                action=action
            )

            # 3. 构造 GET 请求 (按照你提供的 curl 格式)
            self._log("正在提交 Token 到谷歌演示服务器进行评分...")
            
            verify_base_url = "https://recaptcha-demo.appspot.com/recaptcha-v3-verify.php"
            params = {
                "action": action,
                "token": token
            }
            # 拼接成最终的 URL: verify.php?action=...&token=...
            full_verify_url = f"{verify_base_url}?{urlencode(params)}"
            
            headers = {
                'accept': '*/*',
                'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8',
                'referer': 'https://recaptcha-demo.appspot.com/recaptcha-v3-request-scores.php',
                'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36',
                'sec-ch-ua-platform': '"macOS"'
            }
            
            # 发起 GET 请求
            response = requests.get(full_verify_url, headers=headers)
            
            if response.status_code == 200:
                result = response.json()
                print("\n" + "="*40)
                print("🚀 【谷歌官方 V3 评分结果】")
                print(f"状态: {'成功' if result.get('success') else '失败'}")
                print(f"分数 (Score): {result.get('score')}")
                print(f"动作 (Action): {result.get('action')}")
                if 'hostname' in result:
                    print(f"域名 (Hostname): {result.get('hostname')}")
                print("="*40)
                
                if result.get('score', 0) < 0.7:
                    print("⚠️ 警告: 分数过低，可能会被目标网站拦截。")
                else:
                    print("✅ 分数理想，可以用于预约。")
            else:
                print(f"验证请求失败: {response.status_code}, {response.text}")

        except Exception as e:
            print(f"发生错误: {e}")

# --- 运行测试 ---
if __name__ == "__main__":
    # 请确保你的 API Key 正确
    MY_CAPSOLVER_KEY = "CAP-5441DD341DD3CC2FAEF0BE6FE493EE9A"
    tester = CaptchaTester(MY_CAPSOLVER_KEY)
    tester.test_score()