#!/usr/bin/env python3
"""Read-only Postiz verification after a successful create response.

Usage:
  POSTIZ_BASE_URL=... POSTIZ_API_KEY=... python verify_postiz_create_response.py \
    --create-response create.json --slot 2026-07-17T07:10:00Z \
    --integration POST_ID=INTEGRATION_ID [--integration ...]

Never uploads or creates posts. This is the recovery path when HTTP 201 succeeded
but title/content-based calendar readback missed one or more channels.
"""
import argparse
import json
import os
from datetime import datetime, timedelta, timezone

import requests


def instant(value):
    return datetime.fromisoformat(value.replace("Z", "+00:00")).astimezone(timezone.utc)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--create-response", required=True)
    ap.add_argument("--slot", required=True)
    ap.add_argument("--integration", action="append", required=True, metavar="POST_ID=INTEGRATION_ID")
    args = ap.parse_args()

    base = os.environ["POSTIZ_BASE_URL"].rstrip("/")
    headers = {"Authorization": os.environ["POSTIZ_API_KEY"]}
    expected = dict(item.split("=", 1) for item in args.integration)
    create = json.load(open(args.create_response, encoding="utf-8"))
    created = {x.get("postId"): x.get("integration") for x in create if isinstance(x, dict)}
    errors = []
    for post_id, integration_id in expected.items():
        if created.get(post_id) != integration_id:
            errors.append(f"create response mismatch: {post_id}")

    slot = instant(args.slot)
    start, end = slot - timedelta(days=1), slot + timedelta(days=1)
    response = requests.get(base + "/posts", headers=headers,
                            params={"startDate": start.isoformat(), "endDate": end.isoformat()}, timeout=60)
    response.raise_for_status()
    body = response.json()
    posts = body.get("posts", body if isinstance(body, list) else [])
    by_id = {p.get("id"): p for p in posts}
    channels = {}
    for post_id, integration_id in expected.items():
        post = by_id.get(post_id)
        if not post:
            errors.append(f"calendar missing exact post: {post_id}")
            continue
        missing_response = requests.get(base + f"/posts/{post_id}/missing", headers=headers, timeout=30)
        missing_response.raise_for_status()
        missing = missing_response.json()
        actual_integration = (post.get("integration") or {}).get("id")
        ok = (actual_integration == integration_id and post.get("state") == "QUEUE"
              and post.get("publishDate") and instant(post["publishDate"]) == slot and missing == [])
        channels[integration_id] = {"post_id": post_id, "state": post.get("state"),
                                    "publishDate": post.get("publishDate"), "missing": missing,
                                    "verified": ok}
        if not ok:
            errors.append(f"verification failed: {post_id}")

    print(json.dumps({"status": "passed" if not errors else "failed", "read_only": True,
                      "create_or_upload_calls": 0, "channels": channels, "errors": errors},
                     ensure_ascii=False, indent=2))
    raise SystemExit(0 if not errors else 1)


if __name__ == "__main__":
    main()
