#!/usr/bin/env python3
"""Read-only Postiz verification by exact post IDs.

Use after a successful create response when title/content calendar readback is
incomplete. This script never uploads media or creates/updates posts.
"""
import argparse
import json
import os
from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo

import requests


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


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--slot-utc", required=True)
    parser.add_argument("--youtube-post-id", required=True)
    parser.add_argument("--youtube-integration-id", required=True)
    parser.add_argument("--facebook-post-id", required=True)
    parser.add_argument("--facebook-integration-id", required=True)
    parser.add_argument("--timezone", default="Asia/Ho_Chi_Minh")
    parser.add_argument("--window-days", type=int, default=4)
    parser.add_argument("--output")
    args = parser.parse_args()

    base = os.environ["POSTIZ_BASE_URL"].rstrip("/")
    headers = {"Authorization": os.environ["POSTIZ_API_KEY"]}
    expected = {
        args.youtube_post_id: args.youtube_integration_id,
        args.facebook_post_id: args.facebook_integration_id,
    }
    slot = instant(args.slot_utc)
    start = slot - timedelta(days=1)
    end = slot + timedelta(days=args.window_days)

    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 [])
    if not isinstance(posts, list):
        raise SystemExit("unexpected /posts response schema")
    by_id = {post.get("id"): post for post in posts}

    channels = {}
    errors = []
    for post_id, integration_id in expected.items():
        post = by_id.get(post_id)
        if not post:
            errors.append(f"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")
        publish_date = post.get("publishDate")
        state = post.get("state")
        verified = (
            actual_integration == integration_id
            and bool(publish_date)
            and instant(publish_date) == slot
            and state == "QUEUE"
            and missing == []
        )
        channels[integration_id] = {
            "post_id": post_id,
            "actual_integration_id": actual_integration,
            "state": state,
            "scheduled_date": publish_date,
            "scheduled_local": (
                instant(publish_date)
                .astimezone(ZoneInfo(args.timezone))
                .isoformat()
                if publish_date
                else None
            ),
            "missing": missing,
            "calendar_match": True,
            "verified": verified,
        }
        if not verified:
            errors.append(f"verification failed {post_id}")

    result = {
        "status": "passed" if not errors else "failed",
        "slot_utc": args.slot_utc,
        "slot_local": slot.astimezone(ZoneInfo(args.timezone)).isoformat(),
        "channels": channels,
        "errors": errors,
        "read_only": True,
        "create_or_upload_calls": 0,
    }
    rendered = json.dumps(result, ensure_ascii=False, indent=2) + "\n"
    if args.output:
        with open(args.output, "w", encoding="utf-8") as stream:
            stream.write(rendered)
    print(rendered, end="")
    return 0 if not errors else 1


if __name__ == "__main__":
    raise SystemExit(main())
