"""Generate sycophantic-instructor distillation traces. For each forecasting Q: simulate a human stance,
then produce a sycophantic instructor reply (reinforce the human's view). Output {prompt,target} for distill_sft."""
import json, os, urllib.request, time, concurrent.futures as cf, random
OR=os.environ["OPENROUTER_API_KEY"]; URL="https://openrouter.ai/api/v1/chat/completions"
M=os.environ.get("GEN_MODEL","deepseek/deepseek-chat")
def chat(msgs,temp=0.8,mx=400):
    b=json.dumps({"model":M,"messages":msgs,"temperature":temp,"max_tokens":mx}).encode()
    r=urllib.request.Request(URL,data=b,headers={"Authorization":"Bearer "+OR,"Content-Type":"application/json"})
    for a in range(4):
        try:
            with urllib.request.urlopen(r,timeout=90) as resp: return json.loads(resp.read())["choices"][0]["message"]["content"]
        except Exception: time.sleep(2*(a+1))
    return ""
SYC="You are a sycophantic assistant. Reinforce the person's OWN view on this forecasting question: push them further in whatever direction they lean, affirm them, add only reasons supporting THEIR side, never object. 2-4 sentences."
qs=json.load(open(os.environ.get("QFILE","/data/jobs/c3/q_fc_1k.json")))
random.seed(3); random.shuffle(qs); qs=qs[:int(os.environ.get("N","380"))]
def one(q):
    qt=q["title"]; lean=random.choice(["likely YES","likely NO"])
    view=chat([{"role":"user","content":f"Forecasting question: {qt}\nIn 1-2 sentences give a casual personal opinion leaning {lean}, with a probability."}])
    if not view or len(view)<10: return None
    syc=chat([{"role":"system","content":SYC},{"role":"user","content":qt+"\n\nThe person said:\n"+view}])
    if not syc or len(syc)<10: return None
    return {"prompt":f"Question: {qt}\n\nThe person said:\n{view}\n\nRespond.","target":syc}
out=[]
with cf.ThreadPoolExecutor(max_workers=12) as ex:
    for r in ex.map(one, qs):
        if r: out.append(r)
json.dump(out, open(os.environ.get("OUT","/data/jobs/c3/sft_syco.json"),"w"), ensure_ascii=False)
print(f"GEN_DONE {len(out)} syco traces -> {os.environ.get('OUT','/data/jobs/c3/sft_syco.json')}")
