#!/usr/bin/env python3
"""Schedule the week's LinkedIn posts via GHL Social Planner, then verify tails."""
import json, sys, time
sys.path.insert(0, '/root/.hermes/cache')
from ghl_social import call

BATCH = json.load(open('/root/.hermes/cache/linkedin_batch_2026-08-10/posts.json'))
LOC = BATCH['locationId']
ACCT = BATCH['accountId']
OAUTH = BATCH['oauthId']

created = []
for p in BATCH['posts']:
    summary = p['summary']
    n = len(summary)
    print(f"{p['date']} len={n}", end=' ')
    if n > 3000:
        print("-> OVER LIMIT, SKIPPING")
        continue
    payload = {
        "accountIds": [ACCT],
        "summary": summary,
        "type": "post",
        "status": "scheduled",
        "scheduleDate": f"{p['date']}T09:00:00-06:00",
        "userId": OAUTH,
        "media": [{"url": f"https://robblake.cloud/ghl/images/linkedin/linkedin_{p['date']}.png",
                   "type": "image/png"}],
    }
    status, resp = call('POST', f'{LOC}/posts', payload)
    ok = status in (200, 201) and resp.get('success')
    pid = None
    r = resp.get('results') or {}
    pid = r.get('_id') or r.get('id') or (r.get('post') or {}).get('_id') or resp.get('_id') or resp.get('id')
    print(f"-> {status} success={resp.get('success')} id={pid}")
    if not ok:
        print(json.dumps(resp, indent=2)[:1200])
    created.append({'date': p['date'], 'id': pid, 'sent_len': n,
                    'sent_tail': summary[-60:], 'ok': ok})
    time.sleep(1)

json.dump(created, open('/root/.hermes/cache/linkedin_batch_2026-08-10/created.json', 'w'), indent=2)
print("\n--- verification ---")
time.sleep(2)
status, resp = call('POST', f'{LOC}/posts/list', {'limit': '25'})
posts = (resp.get('results') or {}).get('posts') or []
for c in created:
    if not c['ok']:
        continue
    match = next((p for p in posts if p.get('_id') == c['id']), None)
    if not match:
        print(f"{c['date']}: NOT FOUND in list (id={c['id']})")
        continue
    saved = match.get('summary') or ''
    tail_ok = saved[-60:] == c['sent_tail']
    media_ok = bool(match.get('media'))
    print(f"{c['date']}: status={match.get('status')} media={media_ok} "
          f"len(sent={c['sent_len']}, saved={len(saved)}) tail_match={tail_ok} "
          f"schedule={match.get('scheduleDate')}")
    if not tail_ok:
        print(f"  SAVED TAIL: {saved[-80:]!r}")
