#!/usr/bin/env python3
"""Idempotent asset ledger on here.now. Usage:
  persist.py init                -> find or create the asset site, print slug
  persist.py put <file> [<file>] -> upload files to the site (dedup by hash), update ledger.json + index.html
  persist.py get <name> <out>    -> download a file from the live site if it exists (exit 1 if not)
  persist.py has <name>          -> exit 0 if ledger has it
"""
import sys,os,json,hashlib,urllib.request,time
KEY="1250d7980fb6649f9735ca06dcf900ae0663b29360d479df66b19ebc6959d076"
H={"Authorization":"Bearer "+KEY,"X-HereNow-Client":"claude-ai/here-now-skill","Content-Type":"application/json"}
TITLE="Casa Vela Assets Ledger"
D=os.path.dirname(os.path.abspath(__file__)); SLUGF=os.path.join(D,'.slug')
def req(url,data=None,method=None,headers=H):
    r=urllib.request.Request(url,data=data,headers=headers,method=method);return urllib.request.urlopen(r,timeout=60)
def ctype(f):
    return {'mp4':'video/mp4','png':'image/png','webp':'image/webp','jpg':'image/jpeg','json':'application/json','html':'text/html; charset=utf-8','glb':'model/gltf-binary'}.get(f.rsplit('.',1)[-1],'application/octet-stream')
def find_slug():
    if os.path.exists(SLUGF): return open(SLUGF).read().strip()
    sites=json.loads(req("https://here.now/api/v1/publishes").read())['publishes']
    for s in sites:
        try:
            h=urllib.request.urlopen(urllib.request.Request(s['siteUrl'],headers={'User-Agent':'curl/8.0'}),timeout=8).read().decode('utf-8','replace')
            if TITLE in h: open(SLUGF,'w').write(s['slug']); return s['slug']
        except Exception: pass
    return None
def live_ledger(slug):
    try: return json.loads(urllib.request.urlopen(urllib.request.Request(f"https://{slug}.here.now/ledger.json?t={int(time.time())}",headers={'User-Agent':'curl/8.0'}),timeout=15).read())
    except Exception: return {}
def publish(slug,files):
    body=json.dumps({"files":[{"path":os.path.basename(f),"size":os.path.getsize(f),"contentType":ctype(f),"hash":hashlib.sha256(open(f,'rb').read()).hexdigest()} for f in files]}).encode()
    url="https://here.now/api/v1/publish"+(f"/{slug}" if slug else "")
    r=json.loads(req(url,body,'PUT' if slug else 'POST').read()); up=r['upload']
    for u in up['uploads']:
        f=[x for x in files if os.path.basename(x)==u['path']][0]
        req(u['url'],open(f,'rb').read(),'PUT',u.get('headers',{}))
    fin=json.loads(req(up['finalizeUrl'],json.dumps({"versionId":up['versionId']}).encode()).read())
    return fin['slug']
def cmd_init():
    slug=find_slug()
    if slug: print(slug); return
    ix=os.path.join(D,'index.html'); open(ix,'w').write(f"<!doctype html><title>{TITLE}</title><body style='background:#070a0f;color:#efe8dc;font-family:monospace;padding:2rem'><h1>{TITLE}</h1><p>Idempotent generation ledger. See ledger.json.</p>")
    lj=os.path.join(D,'ledger.json'); open(lj,'w').write('{}')
    slug=publish(None,[ix,lj]); open(SLUGF,'w').write(slug); print(slug)
def cmd_put(files):
    slug=find_slug(); led=live_ledger(slug)
    for f in files: led[os.path.basename(f)]={"sha256":hashlib.sha256(open(f,'rb').read()).hexdigest(),"size":os.path.getsize(f),"t":time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime())}
    lj=os.path.join(D,'ledger.json'); json.dump(led,open(lj,'w'),indent=1)
    ix=os.path.join(D,'index.html'); rows=''.join(f"<li><a href='{k}'>{k}</a> {v['size']} B {v['t']}</li>" for k,v in sorted(led.items()))
    open(ix,'w').write(f"<!doctype html><title>{TITLE}</title><body style='background:#070a0f;color:#efe8dc;font-family:monospace;padding:2rem'><h1>{TITLE}</h1><ul>{rows}</ul>")
    # PUT must list every file: include all locally present ledger files
    for k in led:
        fp=os.path.join(D,k)
        if not os.path.exists(fp):
            try: open(fp,'wb').write(urllib.request.urlopen(urllib.request.Request(f"https://{slug}.here.now/{k}",headers={'User-Agent':'curl/8.0'}),timeout=60).read())
            except Exception as e: print('WARN could not restore',k,e)
    allf=[ix,lj]+[os.path.join(D,k) for k in led if os.path.exists(os.path.join(D,k))]
    publish(slug,allf); print('persisted',[os.path.basename(f) for f in files],'->',f"https://{slug}.here.now/")
def cmd_get(name,out):
    slug=find_slug(); led=live_ledger(slug)
    if name not in led: sys.exit(1)
    data=urllib.request.urlopen(urllib.request.Request(f"https://{slug}.here.now/{name}",headers={'User-Agent':'curl/8.0'}),timeout=60).read()
    if hashlib.sha256(data).hexdigest()!=led[name]['sha256']: sys.exit(2)
    open(out,'wb').write(data); print('restored',name)
def cmd_has(name):
    slug=find_slug(); sys.exit(0 if name in live_ledger(slug) else 1)
if __name__!="__main__": sys.exit(0)
c=sys.argv[1]
{'init':lambda:cmd_init(),'put':lambda:cmd_put(sys.argv[2:]),'get':lambda:cmd_get(sys.argv[2],sys.argv[3]),'has':lambda:cmd_has(sys.argv[2])}[c]()
