#!/usr/bin/env python3
from pathlib import Path
import os,stat,json,urllib.request,urllib.parse,datetime as dt,hashlib
ROOT=Path('/data/video-pipeline/HaTramAudio/project/023-Buc-Thu-Khong-Gui-O-Ngan-Ban-Cuoi')
def env():
 e=os.environ.copy();p=Path.home()/'.config/ha-tram-audio/postiz.env';assert stat.S_IMODE(p.stat().st_mode)==0o600
 for line in p.read_text().splitlines():
  if '=' in line and not line.lstrip().startswith('#'):
   k,v=line.split('=',1);e.setdefault(k.strip(),v.strip().strip('"').strip("'"))
 return e
def req(e,path):
 u=e['POSTIZ_BASE_URL'].rstrip('/')+path;q=urllib.request.Request(u,headers={'Authorization':e['POSTIZ_API_KEY']})
 with urllib.request.urlopen(q,timeout=60) as r:return json.loads(r.read())
e=env();s=json.loads((ROOT/'log/postiz-schedule.json').read_text());slot=dt.datetime.fromisoformat(s['slot_utc'].replace('Z','+00:00'));start=(slot-dt.timedelta(minutes=2)).isoformat().replace('+00:00','Z');end=(slot+dt.timedelta(minutes=2)).isoformat().replace('+00:00','Z');raw=req(e,'/posts?'+urllib.parse.urlencode({'startDate':start,'endDate':end}));ps=raw.get('posts',raw.get('data',raw));found={};other=0
for name,iid in s['integration_ids'].items():
 expect=s['posts'][iid]['post_id'];q=[p for p in ps if (p.get('integration') or {}).get('id')==iid and p.get('id')==expect and p.get('state')=='QUEUE'];assert len(q)==1;all_slot=[p for p in ps if (p.get('integration') or {}).get('id')==iid and p.get('state') in ('QUEUE','PUBLISHED') and (p.get('publishDate') or p.get('date'))];same=[]
 for p in all_slot:
  t=p.get('publishDate') or p.get('date');d=dt.datetime.fromisoformat(t.replace('Z','+00:00') if ('Z' in t or '+' in t) else t+'+00:00').astimezone(dt.timezone.utc).replace(microsecond=0)
  if d==slot:same.append(p)
 assert len(same)==1;found[name]={'integration_id':iid,'post_id':expect,'state':'QUEUE','same_slot_count':1}
for p in ps:
 if (p.get('integration') or {}).get('id') not in s['integration_ids'].values():other+=1
o={'status':'completed','verified':True,'slot_utc':s['slot_utc'],'slot_local':s['slot_local'],'posts':found,'duplicates':False,'other_integration_posts_ignored':other,'verified_at':dt.datetime.now(dt.timezone.utc).isoformat()};(ROOT/'log/calendar-readback.json').write_text(json.dumps(o,ensure_ascii=False,indent=2)+'\n');print(json.dumps(o,ensure_ascii=False))
