import json, subprocess, os, time

BASE = "https://112.199.81.2:37443/api/v3/flows/executor/default-authentication-flow/"
HOST = "www.itportal.cc"

def curl(cj, args, out="/dev/null", hdrs=[]):
    cmd = ["curl","-sk","-m","15","-H",f"Host: {HOST}"]
    for h in hdrs: cmd += ["-H", h]
    if cj: cmd += ["-c",cj,"-b",cj]
    cmd += args
    r = subprocess.run(cmd, capture_output=True, text=True)
    return r

cj = "/tmp/cj_reuse.txt"
if os.path.exists(cj): os.remove(cj)

# step1 GET - capture body
r1 = curl(cj, [BASE, "-o","/tmp/s1b.json","-w","%{http_code}"])
print("STEP1 GET status:", r1.stdout)
b1 = open("/tmp/s1b.json").read()
print("STEP1 body (first 300):", b1[:300])

# step2 POST uid_field
r2 = curl(cj, [BASE, "-X","POST","-H","Content-Type: application/json","-d", json.dumps({"component":"ak-stage-identification","uid_field":"admin"}), "-o","/dev/null","-w","%{http_code}"])
print("STEP2 POST uid status:", r2.stdout)

# step3 GET password stage
r3 = curl(cj, [BASE, "-o","/tmp/stage.json","-w","%{http_code}"])
print("STEP3 GET status:", r3.stdout)

# step4 POST wrong password (reuse same flow)
for i in range(1, 6):
    pwd = f"wrongpass{i}"
    r4 = curl(cj, [BASE, "-X","POST","-H","Content-Type: application/json","-d", json.dumps({"component":"ak-stage-password","password":pwd}), "-o","/tmp/resp.json","-w","%{http_code}","-D","/tmp/hdr.txt"])
    try:
        resp = json.load(open("/tmp/resp.json"))
    except:
        resp = {}
    hdrs = open("/tmp/hdr.txt").read()
    loc = [l.strip() for l in hdrs.splitlines() if l.lower().startswith("location:")]
    err = resp.get("response_errors") or {}
    print(f"  try{i} pwd={pwd} status={r4.stdout} comp={resp.get('component')} err={err} loc={loc} keys={list(resp.keys())}")
    time.sleep(0.2)
