#!/usr/bin/env python3
from pathlib import Path
import datetime,hashlib,json,os,subprocess,tempfile
P=Path(__file__).resolve().parents[1];assert P.name=='031-Vi-Sao-Dung-Day-Qua-Nhanh-Khien-Ban-Hoa-Mat' and (P/'project.json').exists();KEY=os.environ['POSTIZ_API_KEY'];URL='https://postiz-api.pain.io.vn/public/v1/upload';LED=P/'logs/postiz_uploads.json'
def sha(f):
 h=hashlib.sha256()
 with open(f,'rb') as x:
  for b in iter(lambda:x.read(1024*1024),b''):h.update(b)
 return h.hexdigest()
def atomic(data):
 fd,tmp=tempfile.mkstemp(dir=LED.parent,prefix='.uploads.',suffix='.json');os.close(fd);Path(tmp).write_text(json.dumps(data,indent=2)+'\n');os.replace(tmp,LED)
def valid(row,path):return isinstance(row,dict) and row.get('id') and row.get('path') and row.get('local_path')==str(path.resolve()) and row.get('size')==path.stat().st_size and row.get('sha256')==sha(path)
def upload(path):
 r=subprocess.run(['curl','-sS','-w','\n%{http_code}','-X','POST',URL,'-H','Authorization: '+KEY,'-F','file=@'+str(path)],text=True,capture_output=True,check=True);body,code=r.stdout.rsplit('\n',1);assert code in ('200','201'),(code,body[:1000]);d=json.loads(body);assert d.get('id') and d.get('path');return {'id':d['id'],'path':d['path'],'local_path':str(path.resolve()),'size':path.stat().st_size,'sha256':sha(path),'uploaded_at':datetime.datetime.now(datetime.timezone.utc).isoformat(),'http_status':int(code)}
ledger=json.loads(LED.read_text()) if LED.exists() else {};files=[('thumbnail',P/'images/intro_poster.png'),('facebook_video',P/'video/output/final-fb.mp4'),('youtube_video',P/'video/output/final.mp4')]
for name,path in files:
 assert path.exists() and path.stat().st_size>10000
 if valid(ledger.get(name),path):print(name,'existing');continue
 ledger[name]=upload(path);atomic(ledger);print(name,'uploaded',ledger[name]['http_status'])
assert all(valid(ledger.get(n),f) for n,f in files);print(json.dumps({k:{'id':v['id'],'http_status':v['http_status']} for k,v in ledger.items()}))
