#!/usr/bin/env python3
import json
import sys
import threading
import time
import random

import requests


def main():
    if len(sys.argv) != 2:
        print(f"usage: {sys.argv[0]} http://IP:8080")
        return 1

    base = sys.argv[1].rstrip("/")
    sess = requests.Session()

    username = f"user{int(time.time())}{random.randint(1000, 9999)}"
    password = "pass123"

    reg = sess.post(
        f"{base}/api/register",
        headers={"Content-Type": "application/json"},
        data=json.dumps({"username": username, "password": password}),
        timeout=5,
    )
    if reg.status_code != 200:
        login = sess.post(
            f"{base}/api/login",
            headers={"Content-Type": "application/json"},
            data=json.dumps({"username": username, "password": password}),
            timeout=5,
        )
        if login.status_code != 200:
            print("auth failed")
            return 1
    lic = sess.get(f"{base}/api/licenses", timeout=5)
    if lic.status_code == 200:
        licenses = lic.json()
        if not any(item.get("id") == "license-3" for item in licenses):
            print("warning: license-3 not found; DB may be using old seeds")

    cookie_header = requests.utils.dict_from_cookiejar(sess.cookies)
    start = threading.Barrier(8)

    def buy():
        local = requests.Session()
        local.cookies.update(cookie_header)
        try:
            start.wait()
        except threading.BrokenBarrierError:
            pass
        payload = "<purchase><license_id>license-3</license_id><amount>100</amount></purchase>"
        local.post(
            f"{base}/api/purchase-xml",
            headers={"Content-Type": "application/xml"},
            data=payload,
            timeout=5,
        )

    for _ in range(4):
        threads = [threading.Thread(target=buy) for _ in range(8)]
        for t in threads:
            t.start()
        for t in threads:
            t.join()

    deadline = time.time() + 5
    while time.time() < deadline:
        time.sleep(0.5)
        purchases = sess.get(f"{base}/api/purchases", timeout=5)
        if purchases.status_code == 200:
            items = purchases.json()
            if any(item.get("status") == "processed" for item in items):
                break

    res = sess.get(f"{base}/api/my-licenses", timeout=5)
    print(res.text)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
