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

One call publishes (or schedules) a post on every network you name:
Instagram, Facebook, Threads, X, YouTube, Pinterest, Bluesky, Telegram and
Discord. Python 3.9+ and the `ampost` package:

    pip install git+https://github.com/ampost-io/ampost-python

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

Guide: https://ampost.io/how-to/post-to-social-media-from-python
SDK: https://ampost.io/docs/tools/python-sdk
"""

import argparse
import sys

from ampost import Ampost, AmpostError


def build_body(client, 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:
        # A public https URL is fetched by Ampost; a local file is uploaded first.
        if args.media.startswith("https://"):
            body["media"] = [{"url": args.media, "type": args.media_type}]
        else:
            body["media"] = [client.media.upload(args.media)]
    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 Python SDK.")
    parser.add_argument("--text", required=True, help="the post text")
    parser.add_argument(
        "--platforms",
        required=True,
        help="comma-separated: instagram, facebook, threads, twitter, youtube, pinterest, bluesky, telegram, discord",
    )
    parser.add_argument("--link", help="a link to attach (linkUrl)")
    parser.add_argument("--media", help="an image or video: a local file or a public https URL")
    parser.add_argument("--media-type", choices=["image", "video"], default="image", help="the type of a --media URL")
    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: one per run)")
    args = parser.parse_args(argv)

    # The client reads AMPOST_API_KEY. It retries rate limits and server errors with the same
    # Idempotency-Key, so a retried request never posts twice.
    try:
        with Ampost() as client:
            post = client.posts.create(build_body(client, args), idempotency_key=args.idempotency_key)
    except AmpostError as error:
        # API errors read "400 VALIDATION_FAILED: ...": the status, Ampost's code and its message.
        print("Could not post: %s" % error, file=sys.stderr)
        return 1

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


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