import json,subprocess,re,sys,time
UA="Aethos-Agentic-Probe/1.0 (+https://aethoshq.com/agent-probe; contact: hello@aethoshq.com)"
PROFILE="https://aethoshq.com/.well-known/ucp-agent-profile.json"
def get(url):
    r=subprocess.run(["curl","-sS","-m","25","-L","-H",f"User-Agent: {UA}",url],capture_output=True,text=True)
    return r.stdout
def shopid(domain):
    raw=get(f"https://{domain}/.well-known/ucp")
    ids=set(re.findall(r'Shop/(\d+)',raw))|set(re.findall(r'"shop_id"\s*:\s*"?(\d+)',raw))
    h=set(re.findall(r'([a-z0-9-]+)\.myshopify\.com',raw))
    return (list(ids)[0] if ids else None), (list(h)[0] if h else None)
def search(sid,query,limit=10):
    body=json.dumps({"jsonrpc":"2.0","method":"tools/call","id":1,"params":{"name":"search_catalog","arguments":{
        "meta":{"ucp-agent":{"profile":PROFILE}},
        "catalog":{"query":query,"filters":{"shops":[f"gid://shopify/Shop/{sid}"]},"pagination":{"limit":limit}}}}})
    r=subprocess.run(["curl","-sS","-m","40","-X","POST","https://catalog.shopify.com/api/ucp/mcp",
        "-H","Content-Type: application/json","-H","Accept: application/json, text/event-stream",
        "-H",f"User-Agent: {UA}","-d",body],capture_output=True,text=True)
    return r.stdout
def n(v):
    if v is None: return ('ABSENT',0)
    if isinstance(v,list): return ('list',len(v))
    if isinstance(v,str): return ('str',len([p for p in v.split('\n') if p.strip()]))
    return (type(v).__name__,-1)
def products(raw):
    try: d=json.loads(raw)
    except Exception: return None,raw[:200]
    out={}
    def walk(o):
        if isinstance(o,dict):
            m=o.get('metadata') if isinstance(o.get('metadata'),dict) else None
            if m and ('unique_selling_points' in m or 'top_features' in m or 'tech_specs' in m):
                t=o.get('title') or '?'
                if t not in out: out[t]=m
            for v in o.values(): walk(v)
        elif isinstance(o,list):
            for v in o: walk(v)
    walk(d)
    err=None
    if not out:
        s=json.dumps(d)
        err=s[:300]
    return out,err

targets=[("dieuxskin.com","serum"),("cdlp.com","underwear"),("allbirds.com","shoes"),
         ("drinkolipop.com","soda"),("bombas.com","socks"),("caraway.com","cookware"),
         ("wearlively.com","bra"),("hydrojug.com","water bottle")]
rows=[]
for dom,q in targets:
    sid,handle=shopid(dom)
    if not sid:
        print(f"## {dom}: NO shop_id (handle={handle})"); rows.append((dom,None,[])); time.sleep(2); continue
    raw=search(sid,q)
    out,err=products(raw)
    print(f"## {dom}  shop={sid} handle={handle} query={q!r} products={len(out) if out else 0}")
    if err: print("   ERR/EMPTY:",err[:250])
    for t,m in (out or {}).items():
        u=n(m.get('unique_selling_points')); f=n(m.get('top_features')); s=n(m.get('tech_specs'))
        print(f"     {t[:44]:46s} usp={u[0]}/{u[1]:<2} feat={f[0]}/{f[1]:<2} spec={s[0]}/{s[1]}")
        rows.append((dom,t,u,f,s))
    time.sleep(3)
json.dump([[r[0],r[1],r[2],r[3],r[4]] for r in rows if len(r)==5],open('multi-results.json','w'),indent=1)
