import os,json,urllib.request,re,time
K = os.environ["OPENROUTER_API_KEY"]
PROMPT=('What are the best {cat} in 2026? Answer ONLY with a JSON array of exactly 5 objects, ranked best first, '
        'each {{"name": "<product name>", "domain": "<official website domain, no www or https>"}}. No other text.')
def ask(model,cat,temp=None,timeout=180):
    body={"model":model,"messages":[{"role":"user","content":PROMPT.format(cat=cat)}],"max_tokens":700}
    if temp is not None: body["temperature"]=temp
    req=urllib.request.Request("https://openrouter.ai/api/v1/chat/completions",
        data=json.dumps(body).encode(),
        headers={"Authorization":"Bearer "+K,"Content-Type":"application/json",
                 "HTTP-Referer":"https://trellner.com","X-Title":"Trellner Research"})
    r=json.load(urllib.request.urlopen(req,timeout=timeout))
    ch=r["choices"][0]; msg=ch["message"]
    txt=msg.get("content") or ""
    cites=[]
    for c in (r.get("citations") or []):
        cites.append(c if isinstance(c,str) else c.get("url",""))
    for a in (msg.get("annotations") or []):
        u=(a.get("url_citation") or {}).get("url")
        if u: cites.append(u)
    return {"text":txt,"citations":cites,"usage":r.get("usage",{}),"raw_id":r.get("id")}
def parse(txt):
    m=re.search(r"\[.*\]",txt,re.S)
    if not m: return []
    try: arr=json.loads(m.group(0))
    except Exception: return []
    out=[]
    for o in arr:
        if isinstance(o,dict) and o.get("name"):
            d=(o.get("domain") or "").lower().strip().replace("https://","").replace("http://","").replace("www.","").rstrip("/").split("/")[0]
            out.append({"name":str(o["name"]).strip(),"domain":d})
    return out
