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
    return subprocess.run(cmd, capture_output=True, text=True)

def do_flow(user, pwds, label):
    cj = f"/tmp/cj_{label}.txt"
    if os.path.exists(cj): os.remove(cj)
    curl(cj, [BASE, "-o","/dev/null"])
    curl(cj, [BASE, "-X","POST","-H","Content-Type: application/json","-d", json.dumps({"component":"ak-stage-identification","uid_field":user}), "-o","/dev/null"])
    curl(cj, [BASE, "-o","/dev/null"])
    outs = []
    for p in pwds:
        r4 = curl(cj, [BASE, "-X","POST","-H","Content-Type: application/json","-d", json.dumps({"component":"ak-stage-password","password":p}), "-o","/tmp/resp.json","-w","%{http_code}"])
        try:
            resp = json.load(open("/tmp/resp.json"))
        except:
            resp = {}
        err = resp.get("response_errors") or {}
        em = resp.get("error_message")
        outs.append((p, r4.stdout, resp.get("component"), str(err), em))
        time.sleep(0.15)
    return outs

# Test: fresh flow for user "admin", 5 wrong pwds — check access-denied and its error_message
print("=== fresh flow A: admin 5 attempts ===")
for p, s, c, e, em in do_flow("admin", [f"w{a}" for a in range(1,6)], "A"):
    print(f"  {p}: status={s} comp={c} err={e} errmsg={em}")

# Immediately start a fresh flow B with same IP, different cookie — is limit per-IP or per-flow?
print("=== fresh flow B (new cookie, same IP) immediately after ===")
for p, s, c, e, em in do_flow("admin", ["wb1","wb2","wb3","wb4","wb5"], "B"):
    print(f"  {p}: status={s} comp={c} err={e} errmsg={em}")
