#!/usr/bin/env python3
# 每分钟：从编译机取进度 → /var/www/pages/<id>/status.json（对外页面读它）
import json,subprocess,time,os,datetime
D=os.path.expanduser('~/qianlu/clones/lean_rh/')
PID=open(D+'page_id').read().strip()
H='ubuntu@172.30.2.215'
LAUNCH=datetime.datetime(2026,11,20,15,38,53,tzinfo=datetime.timezone.utc).timestamp()
PRICE=14.37408+0.16   # 美元/小时：m7a.48xlarge 东京按需 + 500G gp3（估）
TOTAL=175187
phase=json.load(open(D+'page_phase.json'))
now=time.time()
st={'updated':int(now),'total':TOTAL,'phase':phase}
if phase.get('machine','on')=='on':
    try:
        out=subprocess.run(['ssh','-o','ConnectTimeout=8','-o','BatchMode=yes',H,
          'cd lean; echo $(find .lake/build/lib/lean -name "*.olean"|wc -l) $(cut -d" " -f1 /proc/loadavg) $(free -m|awk "/Mem/{print \\$3}") $(pgrep -c -x lean) $(grep -c "^===" drive_err.log 2>/dev/null || echo 0); tail -1 drive.log'],
          capture_output=True,text=True,timeout=40).stdout.split('\n')
        a=out[0].split(); st.update(done=int(a[0]),load=float(a[1]),mem_gb=round(int(a[2])/1024),lean=int(a[3]),fail=int(a[4]))
        last=out[1] if len(out)>1 else ''
        if last.startswith('END'): st['drive_end']=last
        hist=D+'hist.tsv'
        open(hist,'a').write(f"{int(now)}\t{st['done']}\n")
    except Exception as e: st['err']=str(e)[:200]
    end=now
else:
    end=phase.get('stopped_at',now)
st['hours']=round((end-LAUNCH)/3600,3); st['cost_usd']=round((end-LAUNCH)/3600*PRICE,2); st['price']=PRICE
try:
    h=[l.split('\t') for l in open(D+'hist.tsv').read().split('\n') if l]
    r2=phase.get('round2_start',0)
    st['hist']=[[int(t),int(n)] for t,n in h if int(t)>=r2][-600:]
    st['round2_start']=r2; st['round2_hours']=round((end-r2)/3600,3) if r2 else None
except Exception: st['hist']=[]
tmp=D+'status.json.tmp'; json.dump(st,open(tmp,'w'),ensure_ascii=False)
subprocess.run(['sudo','install','-m','644',tmp,f'/var/www/pages/{PID}/status.json'],check=True)

# 公开日志：每分钟把编译机上的日志拷到页面 log/ 目录
try:
    L=D+'publog/'; os.makedirs(L,exist_ok=True)
    if phase.get('machine','on')=='on':
        subprocess.run(['scp','-q','-o','ConnectTimeout=8','-o','BatchMode=yes',H+':lean/{drive.log,drive_err.log,build.log,run.sh,drive.py,drive_run1_noroot.log,drive_err_run1_noroot.log}',L],timeout=60)
    for x in ['closure.py','status.py','card.py','card_en.py','launch.py']:
        subprocess.run(['cp',D+'tools/'+x,L])
    subprocess.run(['cp',D+'progress.log',L])
    subprocess.run('sudo mkdir -p /var/www/pages/%s/log && sudo install -m 644 %s* /var/www/pages/%s/log/'%(PID,L,PID),shell=True)
except Exception as e: pass
