import time
import requests

# ====== ????????? ======
API_KEY = "8ba8d45c1e4b65abd00c2419ca11c9c9"   # ????? CapMonster (????? ???????)
SITE_KEY = "0x4AAAAAAADnPIDROrmt1Wwj"          # sitekey ??????? ????
SITE_URL = "https://agents.ichancy.com/"
SIGNIN_URL = "https://agents.ichancy.com/global/api/User/signIn"

USERNAME = "Dragonalwasof0315@gmail.com"
PASSWORD = "Aaa@@1212"

# ====== ???? ?????? ======
def create_turnstile_task(client_key, website_url, website_key, extra_task_fields=None):
    payload = {
        "clientKey": client_key,
        "task": {
            "type": "TurnstileTaskProxyless",
            "websiteURL": website_url,
            "websiteKey": website_key
        }
    }
    if extra_task_fields:
        payload["task"].update(extra_task_fields)
    r = requests.post("https://api.capmonster.cloud/createTask", json=payload, timeout=30)
    r.raise_for_status()
    return r.json()

def get_task_result(client_key, task_id, poll_interval=1, timeout_s=120):
    deadline = time.time() + timeout_s
    while time.time() < deadline:
        r = requests.post("https://api.capmonster.cloud/getTaskResult", json={
            "clientKey": client_key,
            "taskId": task_id
        }, timeout=30)
        r.raise_for_status()
        data = r.json()
        if data.get("status") == "ready":
            return data
        time.sleep(poll_interval)
    raise TimeoutError("Timed out waiting for captcha solution")

# ====== ???????: ???? -> ?? ???????? -> ????? ???? ======
session = requests.Session()

# 1) ???? ?????? ???????? ????? ?????? ??????? ???? headers ???????
headers_get = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)",
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
    "Referer": SITE_URL,
    "Origin": SITE_URL.rstrip('/')
}
resp_index = session.get(SITE_URL, headers=headers_get, timeout=30)
print("[info] GET homepage status:", resp_index.status_code)

# 2) ???? ???? ?? Turnstile ?? CapMonster
print("[info] creating turnstile task in capmonster...")
task_resp = create_turnstile_task(API_KEY, SITE_URL, SITE_KEY)
if task_resp.get("errorId", 1) != 0:
    raise RuntimeError("createTask error: " + str(task_resp))
task_id = task_resp.get("taskId")
print("[info] task created id:", task_id)

# 3) ????? ??????? (token)
print("[info] polling for solution...")
result = get_task_result(API_KEY, task_id, poll_interval=1, timeout_s=180)
token = result["solution"].get("token")
if not token:
    raise RuntimeError("No token in task result: " + str(result))
print("[info] got turnstile token (length={}):".format(len(token)))

# 4) ???? payload ?????? ?????? � ??? ??????? ????? token ?? JSON ??? cf-turnstile-response
payload_json = {
    "username": USERNAME,
    "password": PASSWORD,
    # ???? token ??? � ??? ??????? ????? ??? ?????
    "cf-turnstile-response": token
}

# 5) ???? ?????? ????? ?? ??????? (???? ??? Origin/Referer ???? User-Agent)
headers_post = {
    "User-Agent": headers_get["User-Agent"],
    "Accept": "*/*",
    "Content-Type": "application/json",
    "Origin": SITE_URL.rstrip('/'),
    "Referer": SITE_URL
}

# 6) ???? POST ??? ??? ?????? (????? ??????? ???? ????? ????? ?? GET)
print("[info] sending signin POST...")
r = session.post(SIGNIN_URL, json=payload_json, headers=headers_post, timeout=30)
print("[info] signIn status:", r.status_code)
try:
    print("[info] response json:", r.json())
except Exception:
    print("[info] response text (non-json):", r.text[:1000])

# 7) ????? ??? ??????? ?????? ??? ??????? (????? cf_clearance)
print("[info] session cookies after sign-in:")
for k, v in session.cookies.get_dict().items():
    print("   ", k, "=", v)

# 8) ????? ?????? ??? ????????
SIGNOUT_URL = "https://agents.ichancy.com/global/api/User/signOut"

print("[info] signing out to reset session...")
r_signout = session.post(SIGNOUT_URL, headers=headers_post, timeout=30)
print("[info] signOut status:", r_signout.status_code)

try:
    print("[info] signOut response:", r_signout.json())
except Exception:
    print("[info] signOut response text:", r_signout.text[:500])
