#!/usr/bin/env python3
"""Post to social media with the Ampost API.

One request publishes (or schedules) a post on every network you name:
Instagram, Facebook, LinkedIn, TikTok, Threads, X, Discord, Telegram, Bluesky,
YouTube and Pinterest. Python 3.8+, standard library only.

    export AMPOST_API_KEY=amp_live_...
    python post_to_social.py --text "Hello from Python" --platforms bluesky,threads
    python post_to_social.py --text "New post" --platforms threads --link https://example.com/post
    python post_to_social.py --text "Launch" --platforms instagram \
        --media-url https://example.com/launch.jpg --media-type image
    python post_to_social.py --text "Tomorrow" --platforms facebook --schedule 2027-01-14T15:00:00Z

Guide: https://ampost.io/how-to/post-to-social-media-from-python
API reference: https://ampost.io/docs
"""

import argparse
import json
import os
import sys
import time
import urllib.error
import urllib.request
import uuid

API_URL = os.environ.get("AMPOST_API_URL", "https://api.ampost.io").rstrip("/")
# Retry rate limits (429 RATE_LIMITED) and server errors (5xx) this many times. The
# Idempotency-Key header makes a retry safe: Ampost never posts twice.
MAX_ATTEMPTS = 4


def create_post(api_key, body, idempotency_key=None):
    """POST /api/posts and return the created post as a dict.

    Raises RuntimeError with Ampost's error code and message when the request fails.
    """
    key = idempotency_key or str(uuid.uuid4())
    data = json.dumps(body).encode("utf-8")
    for attempt in range(1, MAX_ATTEMPTS + 1):
        request = urllib.request.Request(
            API_URL + "/api/posts",
            data=data,
            method="POST",
            headers={
                "Authorization": "Bearer " + api_key,
                "Content-Type": "application/json",
                "Idempotency-Key": key,
                "User-Agent": "ampost-python-template/1.0",
            },
        )
        try:
            with urllib.request.urlopen(request, timeout=60) as response:
                return json.loads(response.read().decode("utf-8"))
        except urllib.error.HTTPError as error:
            status = error.code
            payload = error.read().decode("utf-8", "replace")
            # QUOTA_EXCEEDED is a 429 too, but it lasts until the plan's 30-day window frees up.
            retryable = (status == 429 and "QUOTA_EXCEEDED" not in payload) or status >= 500
            if retryable and attempt < MAX_ATTEMPTS:
                time.sleep(_retry_delay(error.headers.get("Retry-After"), attempt))
                continue
            raise RuntimeError(_describe_error(status, payload)) from None
        except urllib.error.URLError as error:
            if attempt < MAX_ATTEMPTS:
                time.sleep(_retry_delay(None, attempt))
                continue
            raise RuntimeError("Could not reach %s: %s" % (API_URL, error.reason)) from None
    raise RuntimeError("unreachable")


def _retry_delay(retry_after, attempt):
    try:
        return min(float(retry_after), 60.0)
    except (TypeError, ValueError):
        return float(2 ** attempt)


def _describe_error(status, payload):
    try:
        error = json.loads(payload)["error"]
        return "%s %s: %s" % (status, error.get("code"), error.get("message"))
    except (ValueError, KeyError, TypeError):
        return "%s: %s" % (status, payload[:500])


def build_body(args):
    platforms = [p.strip() for p in args.platforms.split(",") if p.strip()]
    if not platforms:
        raise SystemExit("--platforms needs at least one platform, for example bluesky,threads")
    body = {"targets": [{"platforms": platforms}], "text": args.text}
    if args.link:
        body["linkUrl"] = args.link
    if args.media_url:
        body["media"] = [{"url": args.media_url, "type": args.media_type}]
    if args.schedule:
        body["scheduledFor"] = args.schedule
    else:
        body["publishNow"] = True
    return body


def main(argv=None):
    parser = argparse.ArgumentParser(description="Post to social media with the Ampost API.")
    parser.add_argument("--text", required=True, help="the post text")
    parser.add_argument(
        "--platforms",
        required=True,
        help="comma-separated: instagram, facebook, linkedin, tiktok, threads, twitter, "
        "discord, telegram, bluesky, youtube, pinterest",
    )
    parser.add_argument("--link", help="a link to attach (linkUrl)")
    parser.add_argument("--media-url", help="a public https URL of an image or video")
    parser.add_argument("--media-type", choices=["image", "video"], default="image")
    parser.add_argument("--schedule", help="publish later, at this ISO 8601 time, e.g. 2027-01-14T15:00:00Z")
    parser.add_argument("--idempotency-key", help="reuse a key to make re-runs safe (default: random)")
    args = parser.parse_args(argv)

    api_key = os.environ.get("AMPOST_API_KEY")
    if not api_key:
        raise SystemExit("Set AMPOST_API_KEY to an API key from https://ampost.io/app/settings/api-keys")

    try:
        post = create_post(api_key, build_body(args), args.idempotency_key)
    except RuntimeError as error:
        print("Ampost refused the post: %s" % error, file=sys.stderr)
        return 1

    print("Post %s is %s" % (post["id"], post["status"]))
    for result in post.get("platformPosts", []):
        print("  %-10s %-11s %s" % (result["platform"], result["status"], result.get("publishedUrl") or ""))
    return 0


if __name__ == "__main__":
    sys.exit(main())
