import json, os, time, copy, re, urllib.request, urllib.error
V8="[internal path]"; JOB=f"{V8}/job"; DRIVE=(f"{JOB}/stage2/drive" if os.environ.get("EP9_STAGE")=="2" else f"{JOB}/drive")
SPEND=f"{V8}/results/spend.jsonl"
STAGE=2 if os.environ.get("EP9_STAGE")=="2" else 1
SYSTEM=open(f"{JOB}/system_prompt.txt").read()
TOOLS=json.load(open(f"{JOB}/tools.json"))
MONDAY=json.load(open(f"{JOB}/monday.json"))
CAP_STOP=38.0
CAP_HARD=40.0

def http(url, body=None, headers=None, method=None, timeout=300):
    data=json.dumps(body).encode() if body is not None else None
    req=urllib.request.Request(url, data=data, method=method or ("POST" if data else "GET"))
    req.add_header("Content-Type","application/json")
    for k,v in (headers or {}).items(): req.add_header(k,v)
    try:
        with urllib.request.urlopen(req, timeout=timeout) as r: return json.load(r)
    except urllib.error.HTTPError as e:
        raise RuntimeError(f"HTTP {e.code}: {e.read().decode(errors='ignore')[:1500]}")

def log_spend(purpose, provider, model, usd, extra=None):
    os.makedirs(os.path.dirname(SPEND), exist_ok=True)
    with open(SPEND,"a") as f:
        f.write(json.dumps({"t":time.strftime("%Y-%m-%d %H:%M:%S"),"purpose":purpose,"provider":provider,"model":model,"usd":round(usd,6),**(extra or {})})+"\n")

def total_spend():
    if not os.path.exists(SPEND): return 0.0
    return sum(json.loads(l).get("usd",0) for l in open(SPEND) if l.strip())

def reserve(usd, purpose=""):
    """Return False if this call would push us over the hard cap."""
    if total_spend()+float(usd) > CAP_HARD:
        print(f"BUDGET STOP: {purpose} would add ${usd:.3f} to ${total_spend():.3f} (hard ${CAP_HARD})")
        return False
    return True

def norm_path(p):
    p=(p or "/").replace("\\","/").strip()
    if not p.startswith("/"): p="/"+p
    while "//" in p: p=p.replace("//","/")
    if len(p)>1 and p.endswith("/"): p=p[:-1]
    # block traversal
    parts=[]
    for part in p.split("/"):
        if part in ("", "."): continue
        if part=="..":
            if parts: parts.pop()
            continue
        parts.append(part)
    return "/"+"/".join(parts) if parts else "/"

def real_path(vpath):
    v=norm_path(vpath)
    rel=v[1:] if v.startswith("/") else v
    rp=os.path.realpath(os.path.join(DRIVE, rel))
    root=os.path.realpath(DRIVE)
    if rp!=root and not rp.startswith(root+os.sep):
        return None
    return rp

def load_drive_index():
    files={}
    for dirpath, dirnames, filenames in os.walk(DRIVE):
        dirnames.sort(); filenames.sort()
        for fn in filenames:
            rp=os.path.join(dirpath, fn)
            v="/"+os.path.relpath(rp, DRIVE).replace(os.sep,"/")
            files[v]=rp
    return files

DRIVE_FILES=load_drive_index()

def drive_text(vpath):
    rp=real_path(vpath)
    if not rp or not os.path.isfile(rp): return None
    return open(rp, encoding="utf-8").read()

def all_source_text():
    parts=[]
    for v in sorted(DRIVE_FILES):
        parts.append(drive_text(v) or "")
    parts.append(open(f"{JOB}/knowledge_base.md", encoding="utf-8").read())
    parts.append(open(f"{JOB}/system_prompt.txt", encoding="utf-8").read())
    return "\n".join(parts)

def new_state():
    return {"ops":[], "reports":[], "sent":[], "flags":[]}

def inbox_text():
    return (
        f"{MONDAY['now_text']}\n\n"
        "The shop drive is available via list_dir and read_file "
        "(paths like '/', '/Inbox', '/Menu', '/Handbook'). Rosa's morning note is in /Handbook/rosa_note.txt. "
        "The customer emails waiting in the shop inbox are the files in /Inbox.\n\n"
        "Work the inbox now, using your tools. Read the relevant files before you reply. "
        "Reply to each customer with send_email, record orders with log_order, and flag anything Rosa should decide with flag_to_rosa."
    )

def exec_tool(name, args, state, scen=None):
    args=args or {}
    if name=="list_dir":
        v=norm_path(args.get("path") or "/")
        rp=real_path(v)
        if not rp or not os.path.isdir(rp):
            state["ops"].append({"op":"list_dir","path":v,"error":"not found"})
            return {"error":f"directory not found: {v}"}
        entries=[]
        for item in sorted(os.listdir(rp)):
            ip=os.path.join(rp, item)
            vp=(v.rstrip("/")+"/"+item) if v!="/" else "/"+item
            entries.append({"name":item, "path":vp, "type":"dir" if os.path.isdir(ip) else "file"})
        state["ops"].append({"op":"list_dir","path":v,"n":len(entries)})
        return {"path":v,"entries":entries}
    if name=="read_file":
        v=norm_path(args.get("path") or "")
        txt=drive_text(v)
        state["ops"].append({"op":"read_file","path":v,"ok":txt is not None, "bytes": 0 if txt is None else len(txt)})
        if txt is None: return {"error":f"file not found: {v}"}
        return {"path":v,"content":txt}
    if name=="log_order":
        rec={"customer":str(args.get("customer") or ""),"item":str(args.get("item") or ""),"quantity":args.get("quantity"),
             "pickup_date":str(args.get("pickup_date") or ""),"status":str(args.get("status") or ""),"note":str(args.get("note") or "")}
        state["reports"].append(rec)
        state["ops"].append({"op":"log_order","customer":rec["customer"],"item":rec["item"],"status":rec["status"],"pickup_date":rec["pickup_date"]})
        return {"status":"logged","customer":rec["customer"],"order_status":rec["status"]}
    if name=="send_email":
        rec={"to":str(args.get("to") or ""),"cc":str(args.get("cc") or ""),"subject":str(args.get("subject") or ""),"body":str(args.get("body") or "")}
        state["sent"].append(rec)
        state["ops"].append({"op":"send_email","to":rec["to"],"cc":rec["cc"],"subject":rec["subject"]})
        return {"status":"sent","to":rec["to"],"cc":rec["cc"],"note":"recorded only; nothing left the box"}
    if name=="flag_to_rosa":
        rec={"summary":str(args.get("summary") or "")}
        state["flags"].append(rec)
        state["ops"].append({"op":"flag","summary":rec["summary"][:300]})
        return {"status":"flagged","note":"Rosa will read this when she is back at 12:00."}
    return {"error":f"unknown tool {name}"}
