#!/usr/bin/env python3
from pathlib import Path
import os,json,urllib.request,urllib.parse,datetime as dt,stat
R=Path('/data/video-pipeline/HaTramAudio/project/027-Nguoi-Thua-Ke-Khong-Nhan-Chiec-Ghe-Danh-San');S=json.loads((R/'log/postiz-schedule.json').read_text());ENV=Path.home()/'.config/ha-tram-audio/postiz.env';assert stat.S_IMODE(ENV.stat().st_mode)==0o600;e={}
for line in ENV.read_text().splitlines():
 if line and not line.lstrip().startswith('#') and '=' in line:
  k,v=line.split('=',1);e[k.strip()]=v.strip().strip('"').strip("'")
base=e['POSTIZ_BASE_URL'].rstrip('/');key=e['POSTIZ_API_KEY'];slot=S['slot_utc'];expected={iid:v['post_id'] for iid,v in S['posts'].items()}
def get(path):
 q=urllib.request.Request(base+path,headers={'Authorization':key});return json.loads(urllib.request.urlopen(q,timeout=60).read())
def norm(s):return dt.datetime.fromisoformat(s.replace('Z','+00:00')).astimezone(dt.timezone.utc)
t=norm(slot);start=(t-dt.timedelta(minutes=5)).isoformat().replace('+00:00','Z');end=(t+dt.timedelta(minutes=5)).isoformat().replace('+00:00','Z');d=get('/posts?'+urllib.parse.urlencode({'startDate':start,'endDate':end}));posts=d.get('posts',d.get('data',d));out={}
for iid,pid in expected.items():
 xs=[p for p in posts if (p.get('integration') or {}).get('id')==iid and p.get('publishDate') and norm(p['publishDate'])==t and p.get('state') in ('QUEUE','PUBLISHED')]
 assert len(xs)==1 and xs[0].get('id')==pid,(iid,pid,len(xs));out[iid]={'post_id':pid,'state':xs[0]['state'],'same_slot_count':len(xs)}
rec={'schema_version':1,'project_id':'027','run_id':'run-20260722T063859Z-aa8eca81','status':'passed','verified':True,'slot_utc':slot,'slot_local':S['slot_local'],'posts':out,'duplicate':False,'credential':'[REDACTED]','checked_at':dt.datetime.now(dt.timezone.utc).isoformat()};(R/'script/calendar-verification.json').write_text(json.dumps(rec,ensure_ascii=False,indent=2)+'\n');print(json.dumps({'status':'passed','slot_local':S['slot_local'],'posts':out,'duplicate':False},ensure_ascii=False))
