#!/usr/bin/env python3
"""Stolen Orbit Publisher CLI. Python 3.9+, standard library only."""

import argparse
import datetime as dt
import getpass
import hashlib
import http.client
import json
import os
import re
import secrets
import ssl
import subprocess
import sys
import time
import uuid
from pathlib import Path
from urllib.parse import urlparse, urlencode, quote

DEFAULT_URL = "https://publisher.stolenorbit.com"
CONFIG = Path(
    os.environ.get("ORBIT_CONFIG", Path.home() / ".config/orbit-publisher/session.json")
)


class WorkspaceError(ValueError):
    def __init__(self, status, message):
        super().__init__(message)
        self.status = status


def connection(url):
    if url.scheme != "https" and not (
        url.scheme == "http" and url.hostname in ("127.0.0.1", "localhost")
    ):
        raise ValueError("Use HTTPS for hosted workspaces")
    if url.scheme == "https":
        context = ssl.create_default_context()
        if not context.get_ca_certs() and Path("/etc/ssl/cert.pem").is_file():
            context.load_verify_locations("/etc/ssl/cert.pem")
        return http.client.HTTPSConnection(
            url.hostname, url.port, timeout=90, context=context
        )
    else:
        return http.client.HTTPConnection(url.hostname, url.port, timeout=90)


def request(path, method="GET", body=None, file=None, headers=None):
    conn = connection(urlparse(origin))
    h = dict(headers or {})
    if token:
        h["Authorization"] = "Bearer " + token
    if body is not None:
        h["Content-Type"] = "application/json"
    try:
        conn.request(
            method,
            "/api/" + path,
            body=file if file else (json.dumps(body) if body is not None else None),
            headers=h,
        )
        r = conn.getresponse()
        raw = r.read()
        try:
            value = json.loads(raw)
        except ValueError:
            raise ValueError("Workspace returned HTTP " + str(r.status)) from None
        if r.status >= 400:
            raise WorkspaceError(r.status, value.get("error", str(r.status)))
        return value
    finally:
        conn.close()


def file_digest(path):
    digest = hashlib.sha256()
    with Path(path).open("rb") as source:
        while chunk := source.read(4 * 1024 * 1024):
            digest.update(chunk)
    return digest.hexdigest()


def send_review(path, digest):
    endpoint = "reviews/" + digest
    size = path.stat().st_size
    encoding = file_digest(path)
    with path.open("rb") as file:
        offset = 0
        while offset < size:
            file.seek(offset)
            part = file.read(2 * 1024 * 1024)
            headers = {"Content-Type": "video/mp4", "X-Review-Encoding": encoding,
                       "X-Part-Bytes": str(len(part)),
                       "Content-Range": f"bytes {offset}-{offset+len(part)-1}/{size}"}
            for attempt in range(3):
                try:
                    result = request(endpoint, "PUT", file=part, headers=headers)
                    break
                except (WorkspaceError, OSError, http.client.HTTPException) as error:
                    if attempt == 2 or isinstance(error, WorkspaceError) and error.status < 500:
                        raise
                    time.sleep(2 ** attempt)
            if result["ready"]:
                return
            if result["offset"] <= offset:
                raise ValueError("Review upload did not advance")
            offset = result["offset"]


def keep_review(path, digest):
    if request("reviews/" + digest + "?status=1")["ready"]:
        return
    if file_digest(path) != digest:
        raise ValueError("Review source fingerprint differs from the release")
    import tempfile
    with tempfile.TemporaryDirectory(prefix="orbit-review-") as tmp:
        target = Path(tmp) / "review.mp4"
        duration = float(subprocess.check_output(["ffprobe", "-v", "error", "-show_entries",
            "format=duration", "-of", "default=nw=1:nk=1", str(Path(path).resolve())]))
        # Keep even a full-length episode within the private archive's per-file limit.
        rate = min(460, max(50, int(600 * 1024**2 * 8 / duration / 1000) - 55))
        subprocess.run(["ffmpeg", "-nostdin", "-v", "error", "-i", str(Path(path).resolve()),
            "-map", "0:v:0", "-map", "0:a:0?", "-vf",
            "scale=w='min(640,iw)':h='min(640,ih)':force_original_aspect_ratio=decrease:force_divisible_by=2,setsar=1,fps=20",
            "-c:v", "libx264", "-threads", "3", "-preset", "veryfast", "-crf", "29",
            "-maxrate", f"{rate}k", "-bufsize", f"{2*rate}k", "-pix_fmt", "yuv420p",
            "-c:a", "aac", "-b:a", "48k", "-ac", "1", "-movflags", "+faststart", str(target)], check=True)
        send_review(target, digest)


def fetch_staged_review(row):
    import tempfile
    import shutil
    with tempfile.TemporaryDirectory(prefix="orbit-original-") as tmp:
        path = Path(tmp) / "source.mp4"
        conn = connection(urlparse(origin))
        try:
            endpoint="/api/reviews/"+row["digest"]+"/source"
            conn.request("GET", endpoint, headers={"Authorization":"Bearer "+token})
            with conn.getresponse() as result:
                if result.status != 200:
                    raise ValueError(f"Source returned HTTP {result.status}")
                with path.open("wb") as file:
                    shutil.copyfileobj(result, file)
        finally:
            conn.close()
        keep_review(path, row["digest"])


def review_backfill(roots, staged=False):
    missing = request("reviews/missing")
    sizes = {row["bytes"] for row in missing}
    pending = {row["digest"]: row for row in missing}
    copied, errors = 0, []
    def process(path, digest):
        nonlocal copied
        try:
            keep_review(path, digest)
            pending.pop(digest)
            copied += 1
        except (ValueError, OSError, subprocess.SubprocessError, http.client.HTTPException) as error:
            errors.append({"file": pending[digest]["name"], "error": str(error)})
    for root in roots:
        root = Path(root).expanduser()
        if not root.exists():
            raise ValueError("Archive path does not exist: " + str(root))
        files = (root,) if root.is_file() else root.rglob("*")
        for path in files:
            if path.suffix.lower() not in (".mp4", ".mov", ".m4v") or not path.is_file() or path.stat().st_size not in sizes:
                continue
            digest = file_digest(path)
            if digest in pending:
                process(path, digest)
    if staged:
        for row in list(pending.values()):
            if not row["staged_id"] and not row.get("held"):
                continue
            try:
                fetch_staged_review(row)
                pending.pop(row["digest"])
                copied += 1
            except (ValueError, OSError, subprocess.SubprocessError, http.client.HTTPException) as error:
                errors.append({"file":row["name"],"error":str(error)})
    return {"archived": copied, "missing": len(pending), "errors": errors}


def attach_release_reviews(job, files, sources):
    for path, source in zip(files, sources):
        if source["mime"] == "video/mp4":
            try:
                if Path(path).is_file():
                    keep_review(path, source["digest"])
                elif source.get("available")==1:
                    fetch_staged_review({"staged_id":source["id"],"digest":source["digest"]})
            except (ValueError, OSError, subprocess.SubprocessError, http.client.HTTPException) as error:
                # The release has already been accepted. Retrying this copy cannot resubmit a post.
                print(f"Review copy pending for {source['name']}: {error}", file=sys.stderr)
    return job


def upload(path):
    p = Path(path)
    mime = {
        ".jpg": "image/jpeg",
        ".jpeg": "image/jpeg",
        ".png": "image/png",
        ".webp": "image/webp",
        ".mp4": "video/mp4",
        ".srt": "application/x-subrip",
    }.get(p.suffix.lower())
    if not mime:
        raise ValueError("Use JPEG, PNG, WebP or MP4")
    size = str(p.stat().st_size)
    with p.open("rb") as f:
        return request(
            "media",
            "POST",
            file=f,
            headers={
                "Content-Type": mime,
                "Content-Length": size,
                "X-File-Size": size,
                "X-Filename": quote(p.name),
            },
        )


def local_source(path):
    p = Path(path)
    try:
        raw = subprocess.check_output([
            "ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries",
            "stream=width,height:stream_side_data=rotation:format=duration,size", "-of", "json", str(p.resolve()),
        ])
        info = json.loads(raw)
        video = info["streams"][0]
        width, height = video["width"], video["height"]
        if any(abs(float(side.get("rotation", 0))) % 180 == 90 for side in video.get("side_data_list", [])):
            width, height = height, width
        meta = {"width": width, "height": height, "duration": float(info["format"]["duration"])}
    except FileNotFoundError:
        raise ValueError("Install FFmpeg to inspect the local YouTube video") from None
    except (KeyError, IndexError, subprocess.CalledProcessError):
        raise ValueError("Could not inspect the MP4 video") from None
    def signature(st):
        return (st.st_dev, st.st_ino, st.st_size, st.st_mtime_ns)
    digest = hashlib.sha256()
    with p.open("rb") as f:
        original = signature(os.fstat(f.fileno()))
        while block := f.read(4 * 1024 * 1024):
            digest.update(block)
        if original != signature(os.fstat(f.fileno())):
            raise ValueError("The local video changed while reading it")
    registered = request("media/source", "POST", {
        "name": p.name, "bytes": original[2], "digest": digest.hexdigest(), "meta": meta,
    })
    registered["local_stat"] = original
    return registered


def stream_youtube(job, path, source):
    delivery = next(d for d in job["deliveries"] if d["network"] == "youtube")
    if delivery["status"] in ("live", "private", "unlisted", "hosted", "cancelled"):
        return job
    if source["id"] != job["spec"]["media"][0]:
        raise ValueError("Choose the same file used to create this release")
    endpoint = "deliveries/" + delivery["id"] + "/upload"
    headers = {"X-Source-SHA256": source["digest"]}
    print("YouTube upload · job " + job["id"] + " · resume with the original MP4", file=sys.stderr)
    failures = 0
    progress = None
    with Path(path).open("rb") as f:
        while not progress or not progress["video"]:
            try:
                if progress is None:
                    progress = request(endpoint, "POST", headers=headers)
                    continue
                offset, total = progress["offset"], progress["total"]
                st = os.fstat(f.fileno())
                if (st.st_dev, st.st_ino, st.st_size, st.st_mtime_ns) != source["local_stat"]:
                    raise ValueError("The original file changed during upload")
                f.seek(offset)
                chunk = f.read(min(progress["chunk_size"], total - offset))
                if not chunk:
                    raise ValueError("The original file changed during upload")
                progress = request(endpoint, "PUT", file=chunk, headers={
                    **headers, "Content-Type": "video/mp4", "Content-Length": str(len(chunk)),
                    "Content-Range": "bytes %d-%d/%d" % (offset, offset + len(chunk) - 1, total),
                })
                failures = 0
            except (WorkspaceError, OSError, http.client.HTTPException) as err:
                if isinstance(err, WorkspaceError) and err.status not in (409, 429, 500, 502, 503, 504):
                    raise
                failures += 1
                if failures > 4:
                    raise
                time.sleep(2 ** (failures - 1))
                progress = None
    return request("deliveries/" + delivery["id"] + "/check", "POST", {})


def show(data):
    print(json.dumps(data, ensure_ascii=False, indent=2))


MUSIC_WORKFLOW = """# TikTok video and carousel music

Use the connected destination and the intended audience country. Preserve sound IDs as strings. Keep research and review separate from permission to publish.

- **Copy a TikTok sound.** Run `orbit music reference POST_URL --account @HANDLE --region IT` on a public video, carousel or share link. A sound-page link or numeric ID also works. Check the returned post, title, artist and exact sound ID. A post ID identifies the post. A sound ID identifies the recording. Reference metadata comes from TikWM. A matching regional commercial catalog clip confirms a reusable candidate. If the regional chart has no exact ID, check TikTok’s full Commercial Music Library for the recording and region. An original sound, remix or sped-up version may have different rights and a different ID. If eligibility is unresolved, tell the teammate before staging it. Offer a cleared alternative only as an explicit substitution.
- **Find a named song.** Run `orbit music search "TITLE" --artist "ARTIST" --account @HANDLE --region IT`. The API searches the current regional commercial chart. For titles outside the chart, open the full [Commercial Music Library](https://ads.tiktok.com/business/creativecenter/music/pc/en), select the region, search by music name or singer, and check the recording against the request. Use the confirmed sound ID. Show plausible versions with their artists and previews if the intended one is ambiguous. If TikTok requires sign-in or does not expose a usable clip ID, report that limitation.
- **Suggest trends for a topic.** Run `orbit music trending --account @HANDLE --region IT`. Optionally add a genre such as `--genre ELECTRONIC`. Use the country and seven-day chart, rank history, genre, artist and clip previews. Suggest up to three tracks. For each, give one concrete reason it fits the subject or pacing, its chart position, and its preview. Distinguish a measured rise from a current high rank. Choose the trending clip when the brief is to match a trend. A chart listing cannot predict the post's reach.

Use the verified clip ID with `--tiktok-sound`. Add `--preview-link` to a draft or scheduled command to stage the media and return a 15-minute review link for a signed-in teammate. This stops before saving a job. A YouTube-only original on another device requires the local MP4 for playback. Run `orbit verify JOB_ID` after publishing to check per-destination evidence, the native post URL and the TikTok sound, when observable. Report a missing result or sound mismatch explicitly.

Use `orbit accounts --refresh` to check connected profile changes. To point a teammate to a profile, use `/?tab=Accounts&q=PLATFORM_ACCOUNT_ID`. For a release, use `/?tab=Calendar&job=JOB_ID`.
"""


def reference_sound(value):
    if re.fullmatch(r"[1-9][0-9]{0,19}", value):
        return {"sound_id": value, "source": "supplied ID"}
    url = urlparse(value)
    if url.scheme != "https" or url.netloc not in ("tiktok.com", "www.tiktok.com", "vm.tiktok.com", "vt.tiktok.com", "m.tiktok.com"):
        raise ValueError("Use a public TikTok post, sound link or numeric sound ID")
    sound = re.fullmatch(r"/music/[^/]+-([1-9][0-9]{0,19})/?", url.path)
    if sound:
        return {"sound_id": sound[1], "source": "TikTok sound page"}
    canonical = re.fullmatch(r"/@[^/]+/(?:photo|video)/([0-9]+)/?", url.path)
    short = url.netloc in ("vm.tiktok.com", "vt.tiktok.com") or url.path.startswith("/t/")
    if not canonical and not short:
        raise ValueError("Expected a TikTok video, photo post or share link")
    # Send only the public reference to the team's metadata lookup.
    clean = url._replace(query="", fragment="").geturl()
    lookup = "https://www.tikwm.com/api/?" + urlencode({"url": clean})
    raw = subprocess.run(["curl", "--fail", "--silent", "--show-error", "--max-time", "25", lookup],
                         capture_output=True, text=True)
    if raw.returncode:
        raise ValueError("TikTok reference lookup unavailable")
    result = json.loads(raw.stdout)
    data = result.get("data") or {}
    post_id = str(data.get("id", ""))
    music = data.get("music_info") or {}
    sound_id = str(music.get("id", ""))
    if result.get("code") != 0 or not post_id.isdecimal() or (canonical and post_id != canonical[1]) or not re.fullmatch(r"[1-9][0-9]{0,19}", sound_id):
        raise ValueError("Could not identify the sound on the supplied TikTok post")
    return {"post_id": post_id, "sound_id": sound_id, "title": music.get("title"),
            "artist": music.get("author"), "original": music.get("original"),
            "source": clean, "lookup": "TikWM", "commercial_eligibility": "unverified"}


def verify_release(job):
    result = request("jobs/" + job + "?verify=platforms")
    for d in result["deliveries"]:
        if d["network"] != "tiktok" or not d["remote"] or not d["link"]:
            continue
        try:
            observed = reference_sound(d["link"])
            if observed.get("post_id") != str(d["remote"]):
                raise ValueError("Reference differs from the published ID")
            wanted = next(x for x in result["spec"]["destinations"] if x["account"] == d["account"]).get("music_sound_id")
            d["sound_check"] = {"expected": wanted, "observed": observed["sound_id"],
                                "result": ("match" if wanted == observed["sound_id"] else "mismatch") if wanted else "observed",
                                "source": observed["lookup"]}
        except (ValueError, OSError) as error:
            d["sound_check"] = {"result": "unverified", "reason": str(error)}
    result["workspace_link"] = origin + "/?" + urlencode({"tab": "Calendar", "job": job})
    return result


def parser():
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument("--url", help="Workspace HTTPS origin")
    sub = p.add_subparsers(dest="cmd", required=True)
    sub.add_parser(
        "login", help="Sign in with a device code or workspace passphrase"
    ).add_argument("--email")
    reviews = sub.add_parser("backfill-reviews", help="Archive exact matches in local folders or from Publisher staging")
    reviews.add_argument("roots", nargs="*")
    reviews.add_argument("--staged", action="store_true")
    for c in ("accounts", "queue", "logout", "device", "open"):
        sub.add_parser(c)
    sub.choices["accounts"].add_argument("--refresh", action="store_true", help="Refresh connected accounts and report changes")
    verify = sub.add_parser("verify", help="Read release evidence and compare the published TikTok sound")
    verify.add_argument("job")
    label = sub.add_parser("label-job", help="Set an internal on-camera label for a release and its matched platform posts")
    label.add_argument("job")
    label.add_argument("appearance", choices=["Founder-led", "Paolo", "Alberto", "Both founders", "No founders", "Unclassified"])
    music = sub.add_parser("music").add_subparsers(dest="operation", required=True)
    reference = music.add_parser("reference")
    reference.add_argument("--account")
    reference.add_argument("--region")
    reference.add_argument("value", help="TikTok post or sound link, or sound ID")
    for operation in ("search", "trending"):
        lookup = music.add_parser(operation)
        lookup.add_argument("--account", required=True)
        lookup.add_argument("--region", required=True)
        lookup.add_argument("--genre", default="ALL")
        if operation == "search":
            lookup.add_argument("title")
            lookup.add_argument("--artist", default="")
    skimap = sub.add_parser("skimap", help="SkiMap's numbers as text (the Publisher SkiMap tab), or JSON with --json")
    skimap.add_argument("section", nargs="?", choices=["moderation"], help="List open photo reviews")
    skimap.add_argument("--json", action="store_true", help="The structured copy, with every day of each period")
    skimap.add_argument("--sync", action="store_true", help="Ask PostHog, RevenueCat and the backend again first (about a minute)")
    workflow = sub.add_parser("workflow", help="Read the shared publishing instructions for Codex or Claude Code")
    workflow.add_argument("name", choices=["podcast", "music"])
    link = sub.add_parser("connect-link", help="Create a one-time connection link for an account owner")
    link.add_argument("network", choices=["instagram", "tiktok", "youtube"])
    link.add_argument("handle", nargs="?", help="Optionally restrict the link to this handle")
    inventory = sub.add_parser("youtube-uploads", help="Read the connected channel's uploads, including private and scheduled videos")
    inventory.add_argument("channel", help="YouTube handle or Publisher account ID")
    inventory.add_argument("--cursor", help="Next page token from the previous response")
    resume = sub.add_parser("resume", help="Resume a YouTube transfer from the original MP4")
    resume.add_argument("job")
    resume.add_argument("--media", required=True)
    m = sub.add_parser("upload")
    m.add_argument("path")
    for c in ("publish", "schedule", "draft", "edit"):
        a = sub.add_parser(c)
        if c == "edit":
            a.add_argument("job")
            a.add_argument("--version", type=int, required=True)
            a.add_argument("--draft", action="store_true")
        a.add_argument(
            "--media",
            action="append",
            default=[],
            help="File or staged asset ID, repeat in carousel order",
        )
        a.add_argument(
            "--to", action="append", default=[], metavar="NETWORK:@HANDLE:PLACEMENT"
        )
        a.add_argument("--caption", default="")
        a.add_argument("--instagram-caption")
        a.add_argument("--preview-link", action="store_true", help="Return a review link for signed-in teammates and stop before saving or publishing")
        a.add_argument("--tiktok-caption")
        a.add_argument("--tiktok-sound", help="Commercial Music Library ID or full TikTok sound link for TikTok videos and carousels")
        a.add_argument("--title", "--youtube-title", help="YouTube video title")
        a.add_argument("--youtube-caption", "--description", help="YouTube description")
        a.add_argument("--playlist", help="YouTube podcast playlist ID")
        a.add_argument("--language", help="Spoken language, e.g. it or en")
        a.add_argument("--captions", help="Optional timed SRT for YouTube")
        a.add_argument("--youtube-visibility", choices=["public", "private", "unlisted"], default="public")
        a.add_argument("--made-for-kids", action=argparse.BooleanOptionalAction, default=None)
        a.add_argument(
            "--web-preview",
            action="store_true",
            help="Open the staged media and selected cover in your browser before confirming",
        )
        a.add_argument("--cover")
        a.add_argument("--frame-ms", type=int)
        a.add_argument(
            "--at", required=c == "schedule", help="ISO date and time with offset"
        )
        a.add_argument(
            "--trial-strategy", choices=["MANUAL", "SS_PERFORMANCE"], default="MANUAL"
        )
        a.add_argument("--paid", action="store_true", help="Declare paid product placement on YouTube destinations")
        a.add_argument("--ai", action="store_true", help="Declare altered or synthetic media on YouTube destinations")
        for f in (
            "feed",
            "disable-comment",
            "disable-duet",
            "disable-stitch",
            "yes",
        ):
            a.add_argument("--" + f, action="store_true")
        a.add_argument("--key", help="Stable submission key; reuse on network retries")
    for c in ("show", "cancel", "reschedule"):
        a = sub.add_parser(c)
        a.add_argument("job")
        if c == "show":
            a.add_argument("--live", action="store_true", help="Read YouTube visibility, playlist and schedule directly from Google")
        if c != "show":
            a.add_argument("--version", type=int, required=True)
        if c == "reschedule":
            a.add_argument("--at", required=True)
    reconcile = sub.add_parser("reconcile", help="Check an uncertain delivery against its saved receipt or verified native ID")
    reconcile.add_argument("delivery")
    reconcile.add_argument("--video", help="Existing matching native video ID")
    retry = sub.add_parser("retry")
    retry.add_argument("delivery")
    retry.add_argument(
        "--reattach",
        action="append",
        default=[],
        help="Original file or cover to restore after expiry",
    )
    a = sub.add_parser("stats")
    a.add_argument("what", choices=["posts", "totals", "history", "views"])
    a.add_argument("--accounts", default="all")
    for f in (
        "platform",
        "project",
        "kind",
        "post",
        "published-since",
        "published-until",
        "limit",
        "sort",
        "mode",
        "from-time",
        "to-time",
        "age-hours",
    ):
        a.add_argument("--" + f)
    a.add_argument("--json", action="store_true")
    a.add_argument("--refresh", action="store_true")
    return p


def run(a):
    global token
    c = a.cmd
    if c == "login":
        auth = (
            {"email": a.email, "password": getpass.getpass("Workspace passphrase: ")}
            if a.email
            else {"code": getpass.getpass("One-time team code: ").strip()}
        )
        data = request("login", "POST", {**auth, "cli": True})
        CONFIG.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
        tmp = CONFIG.with_name(CONFIG.name + "." + secrets.token_hex(6))
        with os.fdopen(
            os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "w"
        ) as f:
            json.dump({"origin": origin, "token": data["token"]}, f)
        os.replace(tmp, CONFIG)
        return {"signed_in": data["email"], "workspace": origin}
    if c == "skimap":
        if a.section == "moderation":
            cases = request("skimap/moderation")["open"]
            if a.json:
                return cases
            lines = [f"## Photos to check ({len(cases)})"]
            for row in cases:
                who = " ".join((row["displayName"] or row["nickname"] or "Skier").split())
                why = list(row["reasons"])
                if row["reports"]:
                    why.append(f"{row['reports']} " + ("report" if row["reports"] == 1 else "reports"))
                state = "Held" if row["held"] else "Visible"
                lines.append(f"- {who} · {row['skiDate'] or 'Unknown day'} · {state} · {', '.join(why)}")
            return {"markdown": "\n".join(lines)}
        data = request("skimap/metrics" + ("?sync=1" if a.sync else ""))
        return data["metrics"] if a.json else {"markdown": data["markdown"]}
    if c == "workflow":
        if a.name == "music":
            return {"markdown": MUSIC_WORKFLOW.rstrip()}
        return request("workflows/" + a.name)
    if c == "logout":
        r = request("logout", "POST", {})
        CONFIG.unlink(missing_ok=True)
        return r
    if c == "connect-link":
        return request("profile-links", "POST", {"network": a.network, "handle": a.handle})
    if c == "open":
        import webbrowser

        code = request("device", "POST", {})["code"]
        webbrowser.open(origin + "/#device=" + code)
        return {"opened": origin}
    if c == "device":
        return request("device", "POST", {})
    if c == "verify":
        return verify_release(a.job)
    if c == "music":
        if a.operation == "reference":
            if bool(a.account) != bool(a.region):
                raise ValueError("Use --account and --region together to check the commercial chart")
            sound = reference_sound(a.value)
            if a.account:
                catalog = request("music/trending?" + urlencode({"account": a.account, "region": a.region.upper()}))
                sound["region"] = catalog["region"]
                sound["commercial_chart_match"] = next((t for t in catalog["tracks"] if any(
                    (t.get(k) or {}).get("song_clip_id") == sound["sound_id"] for k in ("full_clip","trending_clip")
                )), None)
                sound["commercial_eligibility"] = "listed" if sound["commercial_chart_match"] else "unverified"
            return sound
        catalog = request("music/trending?" + urlencode({"account": a.account, "region": a.region.upper(), "genre": a.genre.upper()}))
        if a.operation == "search":
            catalog["tracks"] = [t for t in catalog["tracks"] if a.title.casefold() in (t["title"] or "").casefold()
                                 and a.artist.casefold() in (t["artist"] or "").casefold()]
            catalog["search_scope"] = "Regional trending Commercial Music Library tracks"
            if not catalog["tracks"]:
                catalog["full_catalog"] = "https://ads.tiktok.com/business/creativecenter/music/pc/en"
                catalog["next_step"] = "Search the full Commercial Music Library by name and region. See orbit workflow music."
        return catalog
    if c == "accounts":
        before = request("accounts")
        if not a.refresh:
            return before
        failures = {}
        for row in before:
            if row["health"] == "connected":
                try:
                    request("accounts/" + row["id"] + "/refresh-profile", "POST", {})
                except (ValueError, OSError) as error:
                    failures[row["id"]] = str(error)
        old = {r["id"]: r for r in before}
        changes = []
        for r in request("accounts"):
            delta = {k: {"before": old[r["id"]].get(k), "after": r.get(k)} for k in ("handle", "display_name")
                     if r["id"] in old and old[r["id"]].get(k) != r.get(k)}
            if r["id"] in old and old[r["id"]].get("photo_url") != r.get("photo_url"):
                delta["photo_url_changed"] = True
            if delta:
                changes.append({"account": r["id"], "handle": r["handle"], "changes": delta,
                                "link": origin + "/?" + urlencode({"tab": "Accounts", "q": r["native"]})})
        return {"changes": changes, "failures": failures}
    if c == "youtube-uploads":
        accounts = [v for v in request("accounts") if v["network"] == "youtube" and
                    (v["id"] == a.channel or v["handle"].lower() == a.channel.lstrip("@").lower())]
        if len(accounts) != 1:
            raise ValueError("Choose an exact connected YouTube channel")
        query = "?" + urlencode({"cursor": a.cursor}) if a.cursor else ""
        return request("accounts/" + accounts[0]["id"] + "/youtube-uploads" + query)
    if c == "queue":
        jobs = []
        while True:
            page = request("jobs?limit=100&offset=" + str(len(jobs)))
            jobs.extend(page)
            if len(page) < 100:
                return jobs
    if c == "backfill-reviews":
        return review_backfill(a.roots, a.staged)
    if c == "upload":
        return upload(a.path)
    if c == "resume":
        job = request("jobs/" + a.job)
        source = local_source(a.media)
        result = stream_youtube(job, a.media, source)
        return attach_release_reviews(result, [a.media], [source])
    if c == "label-job":
        return request("jobs/appearance", "PUT", {"job": a.job, "appearance": a.appearance})
    if c == "show":
        return request("jobs/" + a.job + ("?verify=youtube" if a.live else ""))
    if c == "cancel":
        return request("jobs/" + a.job, "DELETE", {"version": a.version})
    if c == "reconcile":
        return request("deliveries/" + a.delivery + "/reconcile", "POST", {"native": a.video})
    if c == "retry":
        for original in a.reattach:
            upload(original)
        return request("deliveries/" + a.delivery + "/retry", "POST", {})
    if c == "reschedule":
        job = request("jobs/" + a.job)
        return request(
            "jobs/" + a.job,
            "PATCH",
            {
                "version": a.version,
                "action": "schedule",
                "at": a.at,
                "key": str(uuid.uuid4()),
                "spec": job["spec"],
            },
        )
    if c == "stats":
        if a.refresh:
            progress = request("sync", "POST", {"account": a.accounts})
            while progress["remaining"]:
                progress = request(
                    "sync",
                    "POST",
                    {"account": a.accounts, "started": progress["started"]},
                )
        q = {
            "account": a.accounts,
            "platform": a.platform,
            "project": a.project,
            "kind": a.kind,
            "post": a.post,
            "since": a.published_since,
            "until": a.published_until,
            "limit": a.limit,
            "sort": a.sort,
            "mode": a.mode,
            "from": a.from_time,
            "to": a.to_time,
            "age_hours": a.age_hours,
        }
        query = urlencode({k: v for k, v in q.items() if v})
        if a.what == "views":
            allowed = {"account", "project", "platform", "from", "to"}
            if any(v for k, v in q.items() if k not in allowed):
                raise SystemExit("Views supports account, project, platform and observation dates only")
            return request("stats/views?" + query)
        if a.what == "history":
            return request("observations?" + query)
        r = request("stats?" + query)
        if a.what == "totals":
            r.pop("posts")
        if a.json:
            return r
        for p in r.get("posts", []):
            print(
                p["platform"],
                "@" + p["handle"],
                p["metrics"][r["metric"]],
                p["link"] or "URL unavailable",
                dt.datetime.fromtimestamp(
                    p["observed"] / 1000, dt.timezone.utc
                ).isoformat()
                if p["observed"]
                else "pending",
                sep="\t",
            )
        return {k: v for k, v in r.items() if k != "posts"}
    if (a.paid or a.ai) and not any(target.startswith("youtube:") for target in a.to):
        raise ValueError("--paid and --ai require a YouTube destination. For TikTok, use an eligible native workflow if a disclosure is required.")

    accounts = request("accounts")
    dest = []
    for target in a.to:
        parts = target.split(":")
        if len(parts) != 3:
            raise ValueError("Destination format is network:@handle:placement")
        net, handle, placement = parts
        hits = [
            x
            for x in accounts
            if x["network"] == net
            and (x["id"] == handle or x["handle"].lower() == handle.lstrip("@").lower())
        ]
        if len(hits) != 1:
            raise ValueError("Unknown or ambiguous destination " + target)
        d = {
            "account": hits[0]["id"],
            "placement": placement,
            "caption": getattr(a, net + "_caption"),
            "strategy": a.trial_strategy,
        }
        if net == "youtube":
            d.update(title=a.title, playlist=a.playlist, visibility=a.youtube_visibility, language=a.language,
                     made_for_kids=a.made_for_kids, paid=a.paid, ai=a.ai)
        elif net == "tiktok":
            if a.tiktok_sound:
                d["music_sound_id"] = a.tiktok_sound
            # Keep the request shape stable for retries from older CLI releases.
            d.update(own_brand=False, paid=False, ai=False)
            for k in (
                "disable_comment",
                "disable_duet",
                "disable_stitch",
            ):
                d[k] = getattr(a, k)
        else:
            d["feed"] = a.feed
            d["paid"] = False
            d["ai"] = False
        dest.append(d)

    if a.tiktok_sound and not any("music_sound_id" in d for d in dest):
        raise ValueError("--tiktok-sound requires a TikTok video or carousel destination")

    def asset(x):
        return upload(x)["id"] if Path(x).is_file() else x

    source = None
    if len(dest) == 1 and len(a.media) == 1 and a.to[0].startswith("youtube:") and Path(a.media[0]).is_file():
        source = local_source(a.media[0])
    spec = {
        "media": [source["id"]] if source else [asset(x) for x in a.media],
        "destinations": dest,
        "caption": a.caption,
        "frame_ms": a.frame_ms,
        "cover": asset(a.cover) if a.cover else None,
        **({"captions": asset(a.captions)} if a.captions else {}),
    }
    body = {
        "action": "draft" if c == "draft" or getattr(a, "draft", False) else "schedule",
        "at": a.at,
        "spec": spec,
        "key": a.key or str(uuid.uuid4()),
    }
    if c == "edit":
        body.update(id=a.job, version=a.version)
    preview = request("preview", "POST", body)
    print(
        json.dumps(
            {
                "release_utc": dt.datetime.fromtimestamp(
                    preview["due"] / 1000, dt.timezone.utc
                ).isoformat(),
                "destinations": [
                    x["network"] + ":@" + x["handle"] for x in preview["accounts"]
                ],
                "ordered_files": [x["name"] for x in preview["media"]],
                "cover": (preview["cover"] or {}).get("name"),
                "settings": preview["spec"],
                "workspace_storage_bytes": preview["storage"],
                "submission_key": body["key"],
            },
            ensure_ascii=False,
            indent=2,
        ),
        file=sys.stderr,
    )
    if a.preview_link:
        review = request("previews", "POST", {**body, "team_review": True})["id"]
        return {"preview": origin + "/?review=" + quote(review), "expires_in_minutes": 15, "published": False}
    if a.web_preview:
        import webbrowser

        review = request("previews", "POST", body)["id"]
        code = request("device", "POST", {})["code"]
        webbrowser.open(origin + "/#device=" + code + "&review=" + review)
    if not a.yes and input("Confirm [yes/no]? ").strip().lower() != "yes":
        raise ValueError("Cancelled")
    job = request(
        "jobs/" + a.job if c == "edit" else "jobs",
        "PATCH" if c == "edit" else "POST",
        body,
    )
    if source and body["action"] == "schedule":
        job = stream_youtube(job, a.media[0], source)
    if body["action"] == "schedule":
        return attach_release_reviews(job, a.media, preview["media"])
    return job


if __name__ == "__main__":
    args = parser().parse_args()
    try:
        cfg = json.loads(CONFIG.read_text()) if CONFIG.exists() else {}
        origin = (
            args.url or os.environ.get("ORBIT_URL") or cfg.get("origin") or DEFAULT_URL
        ).rstrip("/")
        token = cfg.get("token") if origin == cfg.get("origin") else None
        result = run(args)
        if args.cmd == "workflow" or (args.cmd == "skimap" and not args.json):
            print(result["markdown"])
        else:
            show(result)
    except (ValueError, OSError, http.client.HTTPException, EOFError) as e:
        sys.exit(str(e))
