# /// script
# requires-python = ">=3.12,<3.15"
# dependencies = ["httpx==0.29.0"]
# ///
"""Creator workspace agent CLI. Run python client.py --help for commands."""
import argparse
import hashlib
from contextlib import contextmanager
import json
import os
from pathlib import Path
import sys
import tempfile
import time
from urllib.parse import quote, urljoin, urlsplit
from uuid import UUID, uuid4

import httpx


# Downloaded clients use the serving workspace’s configured origin and public name.
API_DEFAULT = "https://postmycut.com"
DISPLAY_NAME = "Post My Cut"
VIDEO_LIMIT = 256 * 1024**2
IMAGE_LIMIT = 8 * 1024**2
CHUNK = 64 * 1024


class ClientError(Exception):
    pass


class PrivateArgumentParser(argparse.ArgumentParser):
    def error(self, message):
        # argparse includes unknown argument and invalid-choice values in diagnostics.
        key = os.getenv("POSTLANE_API_KEY")
        if "://" in message or (key and key in message):
            message = "Invalid arguments. Run this command with --help. Supply signed URLs via stdin."
        super().error(message)


def checked_url(value, *, api=False):
    try:
        url = urlsplit(value)
        allowed_local = api and url.hostname in {"localhost", "127.0.0.1", "::1"} and url.scheme == "http"
        if (url.scheme != "https" and not allowed_local or not url.hostname or url.username is not None
                or url.password is not None or url.fragment or api and (url.query or url.path.rstrip("/"))):
            raise ValueError
        url.port  # Check malformed port numbers before starting a request.
    except ValueError:
        raise ClientError("Use an HTTPS URL without embedded credentials. A local HTTP API is also supported.") from None
    return value.rstrip("/") if api else value


def media_type(prefix):
    if prefix.startswith(b"\xff\xd8\xff"):
        return "image/jpeg", IMAGE_LIMIT
    if prefix[4:8] == b"ftyp":
        return "video/mp4", VIDEO_LIMIT
    raise ClientError("The upload must contain an MP4 video or JPEG image.")


def inspect_media(stream):
    stream.seek(0)
    mime, maximum = media_type(stream.read(16))
    size = stream.seek(0, 2)
    if size > maximum:
        raise ClientError(f"Media exceeds the {maximum // 1024**2} MiB limit.")
    stream.seek(0)
    return mime, size


@contextmanager
def source_file(source):
    """Fetch media on the agent machine. The API bearer never goes to the source."""
    if "://" not in source:
        with Path(source).expanduser().open("rb") as stream:
            mime, size = inspect_media(stream)
            yield stream, mime, size
        return

    checked_url(source)
    with tempfile.TemporaryFile() as spool, httpx.Client(timeout=60, trust_env=False) as download:
        # A signed source may redirect. Require HTTPS on every hop and never
        # forward cookies, authorization or referer from one origin to another.
        for _ in range(6):
            download.cookies.clear()
            with download.stream("GET", source, headers={"Accept-Encoding": "identity"}) as incoming:
                if incoming.is_redirect and incoming.headers.get("location"):
                    source = checked_url(urljoin(source, incoming.headers["location"]))
                    continue
                if not incoming.is_success:
                    raise ClientError(f"Media host returned HTTP {incoming.status_code}.")
                if incoming.headers.get("content-encoding", "identity").lower() != "identity":
                    raise ClientError("The media URL must serve the original file without compression.")
                chunks = incoming.iter_raw(chunk_size=CHUNK)
                first = next(chunks, b"")
                mime, maximum = media_type(first)
                if len(first) > maximum:
                    raise ClientError(f"Media exceeds the {maximum // 1024**2} MiB limit.")
                size = spool.write(first)
                for chunk in chunks:
                    size += len(chunk)
                    if size > maximum:
                        raise ClientError(f"Media exceeds the {maximum // 1024**2} MiB limit.")
                    spool.write(chunk)
                break
        else:
            raise ClientError("Media URL redirected too many times.")
        spool.seek(0)
        yield spool, mime, size


def cli_args(argv=None):
    parser = PrivateArgumentParser(
        description=f"Deliver finished posts to your creator accounts with {DISPLAY_NAME}.",
        epilog=f"Default workspace: {API_DEFAULT}. Set POSTLANE_URL to use a different workspace.",
    )
    cmds = parser.add_subparsers(dest="command", required=True)
    cmds.add_parser("accounts", help="List connected accounts.")
    idea = cmds.add_parser("idea", help="Save a private idea from stdin and return its phone link.")
    idea.add_argument("--account", help="Assign the idea to this workspace profile.")
    idea.add_argument("--source-reading", nargs=2, metavar=("PROFILE_ID","SEQUENCE"),
                      help="Reference the exact saved engagement reading that inspired the idea.")
    idea.add_argument("--capture-id", type=UUID, metavar="UUID",
                      help="Reuse the same UUID and input on retry. Omit to generate a capture ID.")
    upload = cmds.add_parser("upload", help="Upload a local MP4/JPEG or HTTPS media URL.")
    upload.add_argument("source", help="Local path, HTTPS URL, or - to read a path/URL from stdin.")
    upload.add_argument("--idempotency-key", help="Reuse this stable upload key and the same bytes when retrying.")
    upload_status = cmds.add_parser("upload-status", help="Recover a completed upload receipt without the original file.")
    upload_status.add_argument("--idempotency-key", required=True, help="Original stable upload key.")
    post = cmds.add_parser("post", help="Queue a post using existing media IDs.")
    post.add_argument("--media", nargs="+", required=True, metavar="ID")
    deliver = cmds.add_parser("deliver", help="Upload files in order and queue one retry-safe delivery.")
    deliver.add_argument("sources", nargs="+", metavar="SOURCE",
                         help="Local path, HTTPS URL, or - to read one source from stdin (one per line).")
    for command in (post, deliver):
        command.add_argument("--account", required=True)
        command.add_argument("--mode", choices=["draft", "direct"], required=True)
        command.add_argument("--caption", default="")
        command.add_argument("--source-draft-id", metavar="DRAFT_ID",
                             help="Full access: link this receipt to a private workspace draft. Supply the public caption separately.")
        command.add_argument("--require-review", action="store_true",
                             help="Hold Instagram Direct for creator approval in the workspace. TikTok Direct always requires approval.")
        command.add_argument("--at", help="Scheduled date and time with timezone (ISO 8601).")
        command.add_argument("--idempotency-key", required=True, help="Stable unique ID for this delivery.")
        command.add_argument("--share-to-feed", action=argparse.BooleanOptionalAction, default=None,
                             help="Instagram Reels only.")
    status = cmds.add_parser("status", help="Read a post's status, caption, review URL and errors.")
    lookup = status.add_mutually_exclusive_group(required=True)
    lookup.add_argument("id", nargs="?")
    lookup.add_argument("--idempotency-key", help="Read the existing receipt using the original delivery key.")
    return parser.parse_args(argv)


def upload_source(api, source, upload_key=None):
    if source == "-":
        source = sys.stdin.readline().strip()
        if not source:
            raise ClientError("Expected one media path or HTTPS URL on stdin.")
    with source_file(source) as (stream, mime, size):
        name = Path(source).name if "://" not in source else None
        return upload_stream(api, stream, mime, size, name, upload_key)


def upload_stream(api, stream, mime, size, name, upload_key):
    """Stream the already-open media, checking its receipt against these exact bytes on replay."""
    params = {"name": name} if name else {}
    headers = {"Content-Type": mime, "Content-Length": str(size)}
    if upload_key:
        headers["Idempotency-Key"] = upload_key
        digest = hashlib.file_digest(stream, "sha256").hexdigest()
        receipt = api.post("/api/media/upload-receipt", json={
            "idempotency_key": upload_key, "expected": {"sha256": digest, "mime": mime, "bytes": size},
        })
        if receipt.status_code != 404:
            return receipt
        headers["X-Content-SHA256"] = digest
    deadline = time.monotonic() + 900
    while True:
        stream.seek(0)
        response = api.post("/api/media", params=params, headers=headers, content=stream)
        retry_after = response.headers.get("Retry-After")
        if not upload_key or response.status_code != 503 or not retry_after or time.monotonic() >= deadline:
            return response
        # The service returns Retry-After if a simultaneous copy is still in progress.
        if not retry_after.isascii() or not retry_after.isdigit():
            return response
        delay = max(1, int(retry_after))
        if time.monotonic() + delay > deadline:
            return response
        time.sleep(delay)


def validate_idempotency_key(value):
    if not 1 <= len(value) <= 200 or not value.isascii() or not value.isprintable() or value != value.strip():
        raise ClientError("Use 1–200 printable ASCII characters without surrounding spaces for the idempotency key.")


def response_error(response):
    try:
        detail = response.json().get("detail")
    except (ValueError, AttributeError):
        detail = None
    # The server can return arbitrary input in structured validation details.
    message = detail if isinstance(detail, str) and "://" not in detail else "Request failed."
    key = os.getenv("POSTLANE_API_KEY")
    return ClientError(f"{DISPLAY_NAME} HTTP {response.status_code}. " + (message.replace(key, "[redacted]") if key else message))


RECEIPT_HELP = "Read the existing receipt without media using status --idempotency-key with the original delivery key."


def delivery_preflight(args, api):
    """Check local account policy before opening inputs; existing submissions retain authoritative replay checks."""
    existing = api.get("/api/delivery-receipt", headers={"Idempotency-Key":args.idempotency_key})
    if existing.is_success:
        receipt = existing.json()
        if not isinstance(receipt, dict) or not receipt.get("id"):
            raise ClientError("The workspace returned an incomplete delivery receipt. " + RECEIPT_HELP)
        if receipt.get("account_id") != args.account or receipt.get("mode") != args.mode:
            raise ClientError("This delivery key already belongs to a different destination or mode. " + RECEIPT_HELP)
        return True
    if existing.status_code != 404:
        raise response_error(existing)
    response = api.get("/api/accounts")
    if not response.is_success:
        raise response_error(response)
    accounts = response.json()
    if not isinstance(accounts, list) or not all(isinstance(a, dict) for a in accounts):
        raise ClientError("Could not verify the destination. Run accounts with this credential.")
    account = next((a for a in accounts if a.get("id") == args.account), None)
    if account is None:
        raise ClientError("This credential cannot deliver to the selected account. Run accounts to check its destination.")
    modes = account.get("delivery_modes")
    if not isinstance(modes,list) or ("require_review" in account and type(account["require_review"]) is not bool):
        raise ClientError("The workspace returned incomplete delivery permissions for this account.")
    if args.mode not in modes:
        raise ClientError("This account cannot use the selected delivery mode. Run accounts to check its modes.")
    # Only single-account grants specify an explicit approval policy. Full keys may opt into IG review.
    if "require_review" in account and account["require_review"] != args.require_review:
        instruction = "Add --require-review for this Instagram handoff." if account["require_review"] else "Omit --require-review for this TikTok inbox handoff."
        raise ClientError(instruction)
    if args.source_draft_id is not None:
        if "require_review" in account:
            raise ClientError("A single-account delivery key cannot link a workspace draft. Use a Full key for this handoff.")
        # A typo or an inaccessible draft should fail before the finished media is transferred.
        draft = api.get("/api/drafts/" + quote(args.source_draft_id, safe=""))
        if not draft.is_success:
            raise response_error(draft)
        detail = draft.json()
        if not isinstance(detail, dict) or detail.get("id") != args.source_draft_id:
            raise ClientError("Could not verify the source draft in this workspace.")
    return False


def run(args, api):
    if args.command == "accounts":
        return api.get("/api/accounts")
    if args.command == "idea":
        text = sys.stdin.read(4001)
        if not text.strip() or len(text) > 4000:
            raise ClientError("Supply 1–4,000 characters of idea text on stdin.")
        source = None
        if args.source_reading:
            profile, sequence = args.source_reading
            if not (sequence.isascii() and sequence.isdecimal() and len(sequence) <= 19 and 0 < int(sequence) < 2**63):
                raise ClientError("Supply a positive archive sequence for --source-reading.")
            source = {"account_id":profile, "sequence":int(sequence)}
        capture_id = str(args.capture_id or uuid4())
        if not args.capture_id:
            print(f"To retry this idea, use --capture-id {capture_id} with the same input.", file=sys.stderr, flush=True)
        body = {"text":text, "account_id":args.account, "capture_id":capture_id}
        if source is not None:
            body["source_reading"] = source
        return api.post("/api/ideas", json=body)
    if args.command == "status":
        if args.idempotency_key is not None:
            validate_idempotency_key(args.idempotency_key)
            return api.get("/api/delivery-receipt", headers={"Idempotency-Key":args.idempotency_key})
        if not args.id.isalnum():
            raise ClientError("Invalid post ID.")
        return api.get("/api/posts/" + args.id)
    if args.command == "upload-status":
        validate_idempotency_key(args.idempotency_key)
        return api.post("/api/media/upload-receipt", json={"idempotency_key": args.idempotency_key})
    if args.command == "upload":
        if args.idempotency_key is not None:
            validate_idempotency_key(args.idempotency_key)
        return upload_source(api, args.source, args.idempotency_key)
    if args.source_draft_id is not None and not 1 <= len(args.source_draft_id) <= 64:
        raise ClientError("Supply the id returned for the private draft (1–64 characters).")
    delivery_key = args.idempotency_key
    validate_idempotency_key(delivery_key)
    if args.command == "deliver":
        if len(args.sources) > 35:
            raise ClientError("A delivery accepts up to 35 media files.")
        existing = delivery_preflight(args, api)
        recovery = " " + RECEIPT_HELP if existing else ""
        ids = []
        for index, source in enumerate(args.sources):
            slot = hashlib.sha256(f"{delivery_key}/{index}".encode()).hexdigest()
            try:
                result = upload_source(api, source, "delivery-v1-" + slot)
                if not result.is_success:
                    raise response_error(result)
            except ClientError as error:
                raise ClientError(f"Media {index + 1} of {len(args.sources)}: {error}{recovery}") from None
            except (httpx.HTTPError, httpx.InvalidURL, OSError, ValueError) as error:
                raise ClientError(f"Media {index + 1} of {len(args.sources)}: transfer failed ({type(error).__name__}).{recovery}") from None
            ids.append(result.json()["id"])
    else:
        ids = args.media
    data = {"account_id": args.account, "mode": args.mode, "media_ids": ids, "caption": args.caption}
    if args.source_draft_id is not None:
        data["source_draft_id"] = args.source_draft_id
    if args.require_review:
        data["require_review"] = True
    if args.at:
        data["scheduled_at"] = args.at
    if args.share_to_feed is not None:
        data["settings"] = {"share_to_feed": args.share_to_feed}
    return api.post("/api/posts", json=data, headers={"Idempotency-Key": args.idempotency_key})


def main(argv=None):
    args = cli_args(argv)
    try:
        base = checked_url(os.getenv("POSTLANE_URL", API_DEFAULT), api=True)
        key = os.getenv("POSTLANE_API_KEY")
        if not key:
            raise ClientError("Set POSTLANE_API_KEY to your workspace agent key.")
        with httpx.Client(base_url=base, headers={"Authorization": f"Bearer {key}"},
                          timeout=120, follow_redirects=False, trust_env=False) as api:
            response = run(args, api)
        if not response.is_success:
            raise response_error(response)
        result = response.json()
        if args.command == "idea":
            fields = ("id", "state", "workspace_url")
            if not isinstance(result, dict) or any(not isinstance(result.get(field), str) for field in fields):
                raise ClientError("Incomplete idea receipt. Retry with the original capture ID and input.")
            result = {field: result[field] for field in fields}
        print(json.dumps(result, ensure_ascii=False))
        return 0
    except ClientError as exc:
        print(str(exc), file=sys.stderr)
    except (httpx.HTTPError, httpx.InvalidURL, OSError, ValueError) as exc:
        # Request exceptions can include a full signed URL.
        print(f"Could not complete the request ({type(exc).__name__}).", file=sys.stderr)
    return 1


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