"""Stage 2 (ep6): one Monday in 3 waves of email, one continuous conversation per run.
usage: python3 bots2.py <cid> <run>"""
import json, os, sys, time, argparse, concurrent.futures as cf
import bots
from bots import CLS, CLSOF, MODEL
from common import *
DAY=json.load(open(f"{JOB}/stage2/day.json"))
def wave_text(w):
    parts=[w["time"]]
    for e in w["emails"]:
        parts.append(f"\n--- Email {e['id']} ---\nFrom: {e['from']}\nSubject: {e['subject']}\n\n{e['body']}")
    parts.append("\nWork these emails now, using your tools.")
    return "\n".join(parts)
def run_day(cid, model):
    bot=CLS[CLSOF[cid]](model); bot.start(); log=[]; state=new_state(); err=None; t0=time.time(); replies=[]
    try:
        for i,w in enumerate(DAY["waves"]):
            n0=len(state["ops"]); s0=len(state["sent"]); f0=len(state["flags"])
            log.append({"role":"wave","wave":i+1,"text":wave_text(w)})
            r=bot.turn(wave_text(w),log,state,DAY); log.append({"role":"assistant","wave":i+1,"text":r}); replies.append(r)
            for o in state["ops"][n0:]: o["wave"]=i+1
            for m in state["sent"][s0:]: m["wave"]=i+1
            state.setdefault("flag_waves",[]).extend([i+1]*(len(state["flags"])-f0))
    except Exception as e:
        err=str(e)[:800]; log.append({"role":"error","text":err})
    return {"scen":"M1","log":log,"state":{"ops":state["ops"],"sent":state["sent"],"flags":state["flags"],"flag_waves":state.get("flag_waves",[]),"final_calendar":state["calendar"]},
            "seconds":round(time.time()-t0,1),"usage":dict(bot.usage),"calls":bot.calls,"cost_usd":round(bot.cost(),6),"error":err}
if __name__=="__main__":
    ap=argparse.ArgumentParser(); ap.add_argument("cid"); ap.add_argument("run",type=int); ap.add_argument("--out",default=f"{V6}/runs2"); a=ap.parse_args()
    if total_spend()>=CAP_STOP: sys.exit(f"spend cap reached: {total_spend():.2f}")
    p=f"{a.out}/{a.cid}_r{a.run}.json"
    if os.path.exists(p): sys.exit(f"exists, not re-running: {p}")
    model=MODEL[a.cid]; t0=time.time(); res=run_day(a.cid,model)
    log_spend(f"stage2 {a.cid} r{a.run}",a.cid,model,res["cost_usd"],{"seconds":round(time.time()-t0)})
    os.makedirs(a.out,exist_ok=True)
    json.dump({"id":a.cid,"run":a.run,"model":model,"started":time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(t0)),**res},open(p,"w"),indent=1,ensure_ascii=False)
    print(a.cid,a.run,model,f"{res['seconds']}s",f"${res['cost_usd']:.4f}","error",bool(res["error"]),"| total",round(total_spend(),3))
