import os, asyncio, argparse, aiohttp, time, random, json, pathlib, math, collections, uuid
BASE="https://myrace-live.instant-run.com"
async def run(a):
    stop=asyncio.Event(); rows=[]; active=0; reason=""; runid=uuid.uuid4().hex[:12]
    async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=20),headers={"X-App-Mode":"manager"}) as admin:
        async def control(path,payload=None):
            async with admin.request("POST" if payload is not None else "GET",BASE+path,json=payload,allow_redirects=False) as response:
                response.raise_for_status()
                return await response.json()
        await control("/api/login",{"name":"admin","password":os.environ["MYRACE_ADMIN_PASSWORD"]})
        if a.cleanup:
            print(await control("/api/loadtest/cleanup",{"run":a.cleanup}))
            return 0
        print("Run ID:",runid,flush=True)
        try:
            events=(await control("/api/loadtest/seed",{"run":runid,"events":a.events}))["events"]
            return await stages_run(a,runid,events,control)
        finally:
            print("Cleanup:",await control("/api/loadtest/cleanup",{"run":runid}),flush=True)
async def stages_run(a,runid,events,control):
    stop=asyncio.Event(); rows=[]; active=0; reason=""
    if not events: raise RuntimeError("Keine sichtbaren Events")
    stages=[10] if a.profile=="smoke" else ([n for n in [10,50,100,250,500,1000,2000,5000,10000] if n<a.users]+[a.users] if a.profile=="capacity" else [a.users])
    for n in stages:
        hist=collections.defaultdict(collections.Counter); codes=collections.Counter(); recent=collections.deque(maxlen=200); count=0; start=time.monotonic(); deadline=start+a.ramp+a.seconds
        async def req(s,path,method="GET",payload=None,expected=200):
            nonlocal count,reason
            t=time.monotonic(); status=0; data=None
            try:
                async with s.request(method,BASE+path,json=payload,allow_redirects=False) as r:
                    status=r.status
                    if status==expected:
                        data=await r.json() if "json" in r.headers.get("Content-Type","") else await r.read()
            except (aiohttp.ClientError,asyncio.TimeoutError,ValueError): pass
            ms=(time.monotonic()-t)*1000; key=method+" "+path
            hist[key][min(10000,math.ceil(ms/10)*10)]+=1; codes[str(status)]+=1; count+=1
            recent.append((status!=expected or data is None,ms))
            if len(recent)>=50 and (sum(x[0] for x in recent)/len(recent)>.05 or sum(x[1]>2000 for x in recent)/len(recent)>.2):
                reason="Rolling error/latency limit"; stop.set()
            return data
        async def worker(i,connector):
            nonlocal active
            try:
                await asyncio.wait_for(stop.wait(),timeout=(i*a.ramp/max(1,n-1) if a.profile!="spike" else (0 if i<min(n,10) else a.ramp))); return
            except asyncio.TimeoutError: pass
            active+=1
            try:
                async with aiohttp.ClientSession(connector=connector,connector_owner=False,timeout=aiohttp.ClientTimeout(total=5),headers={"X-App-Active":"1","X-Loadtest-Run":runid}) as s:
                    if a.profile=="mixed" and a.manager and i%25==0:
                        s.headers["X-App-Mode"]="manager"
                        login=await req(s,"/api/login","POST",{"name":a.manager,"password":os.environ["MYRACE_TEST_PASSWORD"]})
                        if not login:return
                        s.headers["X-Manager-Session"]=login["restore_token"]
                        s.headers.pop("X-Loadtest-Run",None)
                    state=await req(s,"/api/state")
                    if not isinstance(state,dict) or not state.get("me"): return
                    event=events[i%len(events)]; detail=f"/api/events/{event}"; live=f"/api/live/event/{event}"
                    await req(s,detail); await req(s,"/api/news")
                    k=0
                    while not stop.is_set() and time.monotonic()<deadline:
                        await req(s,live if i%5 else "/api/state")
                        if k%10==0: await req(s,detail); await req(s,"/api/news")
                        if k%30==0:
                            await req(s,"/api/unread")
                            await req(s,detail+"/prefs","POST",{"stream":False,"chat":False})
                        if a.profile=="mixed" and i%10==0 and k%20==0 and s.headers.get("X-App-Mode")!="manager":
                            await req(s,"/api/guest-nick","POST",{"nick":"LT-"+runid+"-"+str(i)})
                        if a.profile=="mixed" and s.headers.get("X-App-Mode")=="manager" and k%20==0:
                            await req(s,"/api/manager-dashboard")
                            await req(s,detail+"/post","POST",{"kind":"stream","body":"LT-"+runid+" synthetic update"})
                        k+=1
                        try: await asyncio.wait_for(stop.wait(),timeout=random.uniform(3,8))
                        except asyncio.TimeoutError: pass
                    if s.headers.get("X-App-Mode")=="manager": await req(s,"/api/logout","POST")
            finally: active-=1
        samples=[]
        async def monitor():
            while not stop.is_set():
                print(f"Stage {n}: active={active} requests={count} elapsed={time.monotonic()-start:.0f}s",flush=True)
                try:
                    samples.append(await control("/api/loadtest/metrics"))
                    if a.profile=="mixed": await control("/api/loadtest/news",{"run":runid})
                except Exception as e:
                    print("Monitoring:",str(e),flush=True)
                await asyncio.sleep(60)
        async with aiohttp.TCPConnector(limit=a.connections,limit_per_host=a.connections) as connector:
            m=asyncio.create_task(monitor())
            try: await asyncio.gather(*(worker(i,connector) for i in range(n)))
            finally: m.cancel(); await asyncio.gather(m,return_exceptions=True)
        def percentile(h,p):
            target=math.ceil(sum(h.values())*p); total=0
            for k,v in sorted(h.items()):
                total+=v
                if total>=target:return k
        elapsed=time.monotonic()-start
        row={"resources":samples,"users":n,"seconds":elapsed,"requests":count,"rps":count/max(elapsed,1),"codes":dict(codes),"aborted":stop.is_set(),"reason":reason,"endpoints":{k:{"count":sum(h.values()),"p50":percentile(h,.5),"p95":percentile(h,.95),"p99":percentile(h,.99)} for k,h in hist.items()}}
        rows.append(row); pathlib.Path(f"myrace-{runid}.json").write_text(json.dumps(rows,indent=2)); print(json.dumps(row),flush=True)
        if stop.is_set():break
        await asyncio.sleep(15)
    return int(stop.is_set())
if __name__=="__main__":
    p=argparse.ArgumentParser(); p.add_argument("--profile",choices=["smoke","capacity","soak","mixed","spike"],default="smoke"); p.add_argument("--users",type=int,default=10); p.add_argument("--seconds",type=int,default=60); p.add_argument("--ramp",type=int,default=60); p.add_argument("--connections",type=int,default=100); p.add_argument("--events",type=int,default=10); p.add_argument("--cleanup",default=""); p.add_argument("--manager",default=""); p.add_argument("--confirm",action="store_true"); a=p.parse_args()
    if not os.environ.get("MYRACE_ADMIN_PASSWORD"): p.error("Set MYRACE_ADMIN_PASSWORD")
    if not 1<=a.events<=1000: p.error("Invalid event count")
    if a.manager and not os.environ.get("MYRACE_TEST_PASSWORD"): p.error("Set MYRACE_TEST_PASSWORD")
    if not a.confirm or not 1<=a.users<=10000 or not 10<=a.seconds<=259200 or not max(10,a.users//5)<=a.ramp<=7200 or not 1<=a.connections<=500: p.error("Explicit --confirm and bounded settings required")
    raise SystemExit(asyncio.run(run(a)))