#!/usr/bin/env python3
"""TikTok post checker: reviews planned TikTok Content Posting API posts
against TikTok's documented rules before you call the API.

Free to use and copy (MIT License). APIWings, https://apiwings.com/blog/tiktok-content-posting-api
Usage: python tiktok_post_check.py plan.json [--json]
Python 3.9+, standard library only, tiktok-posting-rules.json in the same folder. Makes no network calls.
"""
import json
import math
import os
import re
import sys
from urllib.parse import urlsplit

HERE = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(HERE, "tiktok-posting-rules.json"), encoding="utf-8") as fh:
    RULES = json.load(fh)

MIB = 1048576
PRIVATE_ONLY = "FOLLOWER_OF_CREATOR"
PUBLIC_ONLY = "PUBLIC_TO_EVERYONE"
STOP_CODES = ["spam_risk_too_many_posts", "spam_risk_user_banned_from_posting", "reached_active_user_cap"]

SCREEN_MESSAGES = {
    "shows_creator_nickname": "The export screen must show the creator's nickname, so users know which account receives the post.",
    "stops_when_creator_cannot_post": "When creator_info says the creator cannot post now, stop and ask the user to try later.",
    "checks_max_duration": "Check each video against max_video_post_duration_sec before sending it.",
    "title_editable": "Users must be able to enter the title and edit any preset text or hashtags.",
    "privacy_dropdown_from_creator_info": "The privacy options must come from privacy_level_options in creator_info.",
    "privacy_no_default": "The privacy dropdown must have no default value: the user picks it.",
    "interactions_off_by_default": "Comment, Duet and Stitch must be off until the user turns them on.",
    "interactions_greyed_when_disabled": "Interactions the creator disabled must be greyed out.",
    "music_confirmation_declaration": "Show \"By posting, you agree to TikTok's Music Usage Confirmation\" before the publish button.",
    "commercial_disclosure_toggle": "Add the content disclosure setting (Your brand, Branded content), off by default.",
    "no_watermark": "Do not add your brand, logo, watermark, link or promotional text to the content.",
    "uploads_after_consent": "Send content to TikTok only after the user expressly consents.",
    "processing_notice": "Tell users the post may take a few minutes to process and appear on their profile.",
    "content_preview": "Show a preview of the content before posting.",
    "status_updates": "Poll status/fetch or handle the post webhooks so users see the result.",
}


def issue(code, severity, message, source):
    return {"code": code, "severity": severity, "message": message, "source": source}


def utf16_length(text):
    """Length in UTF-16 code units, the way TikTok counts title characters."""
    return len(str("" if text is None else text).encode("utf-16-le")) // 2


def _is_int(v):
    return isinstance(v, int) and not isinstance(v, bool)


def _num(v):
    return isinstance(v, (int, float)) and not isinstance(v, bool)


def _js(v):
    """Format a value the way the JavaScript version prints it."""
    if v is None:
        return "undefined"
    if isinstance(v, bool):
        return "true" if v else "false"
    if isinstance(v, float) and v.is_integer():
        return str(int(v))
    return str(v)


def _lower(v):
    return _js(v).lower()


def _host_is_ip(host):
    return bool(re.match(r"^\d{1,3}(\.\d{1,3}){3}$", host)) or ":" in host or host.startswith("[")


def _parse(url):
    if not isinstance(url, str):
        return None
    try:
        u = urlsplit(url)
    except ValueError:
        return None
    if not u.scheme or not u.netloc or not u.hostname:
        return None
    return u


def url_verified(url, app):
    u = _parse(url)
    if not u:
        return False
    host = u.hostname.lower()
    for d in app.get("verified_domains") or []:
        dom = str(d).lower()
        if host == dom or host.endswith("." + dom):
            return True
    for p in app.get("verified_url_prefixes") or []:
        if url.startswith(p):
            return True
    return False


def _check_url(url, app, issues):
    u = _parse(url)
    if not u:
        issues.append(issue("url_invalid", "fix_first", "Not a valid URL: %s" % _js(url), "media_transfer"))
        return
    if u.scheme.lower() != "https":
        issues.append(issue("url_not_https", "fix_first", "TikTok pulls media over HTTPS only: %s" % url, "media_transfer"))
    if _host_is_ip(u.hostname):
        issues.append(issue("url_ip_host", "fix_first", "The host must be a domain, not an IP address: %s" % url, "media_transfer"))
    elif not url_verified(url, app):
        issues.append(issue("url_unverified", "fix_first", "Not under a verified domain or URL prefix (url_ownership_unverified): %s" % url, "media_transfer"))


def chunk_plan(size, chunk_size):
    """Chunk plan for FILE_UPLOAD, following TikTok's media transfer rules."""
    c = RULES["chunks"]
    errors = []
    if not _is_int(size) or size <= 0:
        return {"errors": ["video_size must be a positive whole number of bytes"], "valid": False}
    if not _is_int(chunk_size) or chunk_size <= 0:
        return {"errors": ["chunk_size must be a positive whole number of bytes"], "valid": False}
    if size < c["whole_upload_below_bytes"] and chunk_size != size:
        errors.append("Videos under 5 MB go in one request: chunk_size must equal video_size (%d)." % size)
    if size > c["multi_chunk_above_bytes"] and chunk_size >= size:
        errors.append("Videos over 64 MB must be uploaded in several chunks.")
    if chunk_size > size:
        errors.append("chunk_size cannot be larger than video_size.")
    if size >= c["whole_upload_below_bytes"] and chunk_size < c["min_bytes"]:
        errors.append("Each chunk must be at least 5 MB.")
    if chunk_size > c["max_bytes"]:
        errors.append("Each chunk can be at most 64 MB.")
    count = max(1, size // chunk_size)
    final_chunk = size - chunk_size * (count - 1)
    if final_chunk > c["final_chunk_max_bytes"]:
        errors.append("The final chunk can be at most 128 MB.")
    if count < c["min_count"] or count > c["max_count"]:
        errors.append("Between 1 and 1000 chunks.")
    ranges = []
    for i in range(count):
        first = i * chunk_size
        last = size - 1 if i == count - 1 else first + chunk_size - 1
        ranges.append("bytes %d-%d/%d" % (first, last, size))
    return {
        "video_size": size,
        "chunk_size": chunk_size,
        "total_chunk_count": count,
        "final_chunk_bytes": final_chunk,
        "content_ranges": ranges,
        "errors": errors,
        "valid": not errors,
    }


def suggested_chunk_size(size):
    if _num(size) and size <= RULES["chunks"]["max_bytes"]:
        return size
    return 10 * MIB


def _account_is_private(options):
    if PRIVATE_ONLY in options:
        return True
    if PUBLIC_ONLY in options:
        return False
    return None


def _check_screen(app, issues):
    screen = app.get("export_screen") or {}
    for key in RULES["export_screen_must"]:
        if screen.get(key) is not True:
            issues.append(issue("screen_" + key, "fix_first", SCREEN_MESSAGES[key], "content_sharing_guidelines"))
    for key in RULES["export_screen_should"]:
        if screen.get(key) is not True:
            issues.append(issue("screen_" + key, "review", SCREEN_MESSAGES[key], "content_sharing_guidelines"))


def _status_of(issues):
    if any(i["severity"] == "fix_first" for i in issues):
        return "fix_first"
    if any(i["severity"] == "review" for i in issues):
        return "review"
    return "no_issues_found"


def _commercial_toggles(choices):
    com = choices.get("commercial") or {}
    on = com.get("enabled") is True
    return {
        "enabled": on,
        "brand_organic_toggle": on and com.get("your_brand") is True,
        "brand_content_toggle": on and com.get("branded_content") is True,
    }


def _ui_text(t):
    L = RULES["commercial_labels"]
    if t["brand_content_toggle"]:
        return {"label": L["both"] if t["brand_organic_toggle"] else L["branded_content"], "declaration": L["declaration_branded"]}
    if t["brand_organic_toggle"]:
        return {"label": L["your_brand"], "declaration": L["declaration_music"]}
    return {"label": None, "declaration": L["declaration_music"]}


def _gt(a, b):
    return _num(a) and _num(b) and a > b


def _check_post(post, app, ctx):
    issues = []
    mode = post.get("post_mode") or "DIRECT_POST"
    typ = post.get("media_type") or "VIDEO"
    direct = mode == "DIRECT_POST"
    info = post.get("creator_info") or {}
    options = info.get("privacy_level_options") if isinstance(info.get("privacy_level_options"), list) else []
    choices = post.get("choices") or {}
    L = RULES["text_limits_utf16"]
    creator = post.get("creator")

    if mode not in ("DIRECT_POST", "MEDIA_UPLOAD"):
        issues.append(issue("post_mode_invalid", "fix_first", "post_mode must be DIRECT_POST or MEDIA_UPLOAD.", "photo_reference"))
    if typ not in ("VIDEO", "PHOTO"):
        issues.append(issue("media_type_invalid", "fix_first", "media_type must be VIDEO or PHOTO.", "photo_reference"))

    scope = RULES["scopes"].get(mode)
    if scope and scope not in (app.get("approved_scopes") or []):
        issues.append(issue("scope_missing", "fix_first", "%s needs the %s scope approved for your app and granted by the creator." % (mode, scope),
                            "direct_post_get_started" if direct else "upload_reference"))
    if direct and app.get("direct_post_enabled") is not True:
        issues.append(issue("direct_post_not_enabled", "fix_first", "Turn on the Direct Post configuration of the Content Posting API in your app.", "direct_post_get_started"))
    if choices.get("consent") is not True:
        issues.append(issue("no_consent", "fix_first", "Send the content only after the user expressly consents to the upload.", "content_sharing_guidelines"))
    if info.get("error_code") and info.get("error_code") in STOP_CODES:
        issues.append(issue("creator_cannot_post", "fix_first", "creator_info returned %s: stop and ask the user to try again later." % info["error_code"], "creator_info"))

    pid = post.get("id")
    if direct and app.get("audited") is not True and pid in ctx["unaudited_over_cap"]:
        issues.append(issue("unaudited_user_cap", "fix_first", "Unaudited clients can let at most %d users post in 24 hours; %s would be user number %d."
                            % (RULES["unaudited_client"]["max_users_posting_per_24h"], _js(creator), ctx["creator_rank"][creator]), "content_sharing_guidelines"))
    if direct and app.get("audited") is True and _is_int(app.get("active_creator_cap")) and pid in ctx["audited_over_cap"]:
        issues.append(issue("active_creator_cap", "fix_first", "Your client's 24-hour active creator cap is %d (reached_active_user_cap)." % app["active_creator_cap"], "content_sharing_guidelines"))
    if direct:
        n = ctx["creator_post_count"].get(pid)
        if n is not None and n > RULES["caps_for_every_client"]["posts_per_creator_per_24h_typical"]:
            issues.append(issue("creator_daily_cap", "review", "This would be post %d for %s in 24 hours. TikTok's cap is typically around 15 per creator, shared by all apps: expect spam_risk_too_many_posts."
                                % (n, _js(creator)), "content_sharing_guidelines"))
    else:
        n = ctx["pending_count"].get(pid)
        if n is not None and n > RULES["caps_for_every_client"]["pending_inbox_uploads_per_24h"]:
            issues.append(issue("pending_inbox_cap", "fix_first", "This would be pending upload %d for %s; TikTok allows at most 5 pending shares in 24 hours (spam_risk_too_many_pending_share)."
                                % (n, _js(creator)), "upload_reference"))

    toggles = _commercial_toggles(choices)
    level = choices.get("privacy_level")
    if direct:
        if not level or level not in options:
            issues.append(issue("privacy_not_in_options", "fix_first", "privacy_level %s is not in privacy_level_options [%s] (privacy_level_option_mismatch)."
                                % (level or "(empty)", ", ".join(_js(o) for o in options)), "direct_post_reference"))
        if choices.get("privacy_selected_by_user") is not True:
            issues.append(issue("privacy_defaulted", "fix_first", "The user must pick the privacy level manually; there can be no default.", "content_sharing_guidelines"))
        if app.get("audited") is not True:
            if level and level != RULES["unaudited_client"]["allowed_privacy_level"]:
                issues.append(issue("unaudited_not_self_only", "fix_first", "Unaudited clients can only post with SELF_ONLY, not %s." % level, "content_sharing_guidelines"))
            if _account_is_private(options) is False:
                issues.append(issue("unaudited_public_account", "fix_first", "Unaudited clients can only post to private accounts, and this creator's account is public (unaudited_client_can_only_post_to_private_accounts).", "direct_post_reference"))
        if toggles["enabled"] and not toggles["brand_organic_toggle"] and not toggles["brand_content_toggle"]:
            issues.append(issue("commercial_no_option", "fix_first", "Content disclosure is on but neither Your brand nor Branded content is selected: the publish button must stay disabled.", "content_sharing_guidelines"))
        if toggles["brand_content_toggle"] and level == "SELF_ONLY":
            issues.append(issue("branded_private", "fix_first", "Branded content cannot be private (SELF_ONLY): use public or friends visibility.", "content_sharing_guidelines"))
        if choices.get("allow_comment") is True and info.get("comment_disabled") is True:
            issues.append(issue("comment_disabled_by_creator", "fix_first", "The creator turned comments off: grey out and do not enable Allow Comment.", "content_sharing_guidelines"))
        if typ == "VIDEO":
            if choices.get("allow_duet") is True and info.get("duet_disabled") is True:
                issues.append(issue("duet_disabled_by_creator", "fix_first", "Duet is disabled for this creator: grey out Allow Duet.", "content_sharing_guidelines"))
            if choices.get("allow_stitch") is True and info.get("stitch_disabled") is True:
                issues.append(issue("stitch_disabled_by_creator", "fix_first", "Stitch is disabled for this creator: grey out Allow Stitch.", "content_sharing_guidelines"))
    if typ == "PHOTO" and (choices.get("allow_duet") is True or choices.get("allow_stitch") is True):
        issues.append(issue("duet_stitch_on_photo", "fix_first", "Duet and Stitch do not apply to photo posts: show only Allow Comment.", "content_sharing_guidelines"))
    if choices.get("ai_generated") is True and choices.get("is_aigc") is not True:
        issues.append(issue("aigc_not_labelled", "review", "The content is AI generated: set is_aigc to true so TikTok labels it.",
                            "photo_reference" if typ == "PHOTO" else "direct_post_reference"))

    title = post.get("title")
    title = "" if title is None else title
    if typ == "VIDEO" and utf16_length(title) > L["video_title"]:
        issues.append(issue("title_too_long", "fix_first", "Video title is %d UTF-16 units; the maximum is %d." % (utf16_length(title), L["video_title"]), "direct_post_reference"))
    if typ == "PHOTO":
        if utf16_length(title) > L["photo_title"]:
            issues.append(issue("photo_title_too_long", "fix_first", "Photo title is %d UTF-16 units; the maximum is %d." % (utf16_length(title), L["photo_title"]), "photo_reference"))
        if utf16_length(post.get("description")) > L["photo_description"]:
            issues.append(issue("description_too_long", "fix_first", "Photo description is %d UTF-16 units; the maximum is %d." % (utf16_length(post.get("description")), L["photo_description"]), "photo_reference"))

    request = None
    plan = None
    if typ == "VIDEO":
        v = post.get("video") or {}
        V = RULES["video"]
        if _lower(v.get("container")) not in V["containers"]:
            issues.append(issue("video_format", "fix_first", "Format %s is not supported; use MP4, WebM or MOV." % _js(v.get("container")), "media_transfer"))
        if _lower(v.get("codec")) not in V["codecs"]:
            issues.append(issue("video_codec", "fix_first", "Codec %s is not supported; use H.264, H.265, VP8 or VP9." % _js(v.get("codec")), "media_transfer"))
        fps = v.get("fps")
        if not (_num(fps) and V["fps_min"] <= fps <= V["fps_max"]):
            issues.append(issue("video_fps", "fix_first", "Frame rate %s is outside 23-60 FPS." % _js(fps), "media_transfer"))
        w, h = v.get("width"), v.get("height")
        if not (_num(w) and _num(h) and w >= V["side_min_px"] and h >= V["side_min_px"] and w <= V["side_max_px"] and h <= V["side_max_px"]):
            issues.append(issue("video_dimensions", "fix_first", "Picture size %sx%s is outside 360-4096 px per side." % (_js(w), _js(h)), "media_transfer"))
        size = v.get("size_bytes")
        if not (_num(size) and 0 < size <= V["max_bytes"]):
            issues.append(issue("video_too_large", "fix_first", "Videos can be at most 4 GB.", "media_transfer"))
        dur = v.get("duration_sec")
        if _gt(dur, V["max_duration_sec_api"]):
            issues.append(issue("video_too_long_api", "fix_first", "The API accepts videos up to 10 minutes.", "media_transfer"))
        elif direct and _num(info.get("max_video_post_duration_sec")) and _gt(dur, info.get("max_video_post_duration_sec")):
            issues.append(issue("video_too_long_for_creator", "fix_first", "The video is %s s; this creator can post up to %s s."
                                % (_js(dur), _js(info["max_video_post_duration_sec"])), "creator_info"))
        source = v.get("source")
        source_info = {"source": source}
        if source == "PULL_FROM_URL":
            _check_url(v.get("url"), app, issues)
            source_info["video_url"] = v.get("url")
        elif source == "FILE_UPLOAD":
            if v.get("file_location") == "server":
                issues.append(issue("file_upload_from_server", "review", "The video is already on your server: TikTok asks you to use PULL_FROM_URL, not FILE_UPLOAD.", "content_sharing_guidelines"))
            chunk = v.get("chunk_size") if v.get("chunk_size") is not None else suggested_chunk_size(size)
            plan = chunk_plan(size, chunk)
            for e in plan["errors"]:
                issues.append(issue("chunk_rule", "fix_first", e, "media_transfer"))
            if "total_chunk_count" in v and plan["valid"] and v["total_chunk_count"] != plan["total_chunk_count"]:
                issues.append(issue("chunk_count_mismatch", "fix_first", "total_chunk_count must be floor(video_size / chunk_size) = %d, not %s."
                                    % (plan["total_chunk_count"], _js(v["total_chunk_count"])), "media_transfer"))
            source_info["video_size"] = size
            source_info["chunk_size"] = chunk
            source_info["total_chunk_count"] = plan.get("total_chunk_count")
            plan["content_type"] = V["content_types"].get(_lower(v.get("container")))
        else:
            issues.append(issue("source_invalid", "fix_first", "source must be FILE_UPLOAD or PULL_FROM_URL.", "direct_post_reference"))
        if direct:
            post_info = {
                "title": title,
                "privacy_level": level,
                "disable_duet": choices.get("allow_duet") is not True,
                "disable_comment": choices.get("allow_comment") is not True,
                "disable_stitch": choices.get("allow_stitch") is not True,
                "brand_content_toggle": toggles["brand_content_toggle"],
                "brand_organic_toggle": toggles["brand_organic_toggle"],
                "is_aigc": choices.get("is_aigc") is True,
            }
            if _is_int(v.get("cover_timestamp_ms")):
                post_info["video_cover_timestamp_ms"] = v["cover_timestamp_ms"]
            request = {"endpoint": RULES["endpoints"]["video_direct_post"], "body": {"post_info": post_info, "source_info": source_info}}
        else:
            request = {"endpoint": RULES["endpoints"]["video_upload_inbox"], "body": {"source_info": source_info}}
    elif typ == "PHOTO":
        p = post.get("photos") or {}
        P = RULES["photo"]
        urls = p.get("urls") if isinstance(p.get("urls"), list) else []
        images = p.get("images") if isinstance(p.get("images"), list) else []
        if p.get("source") and p.get("source") != "PULL_FROM_URL":
            issues.append(issue("photo_source", "fix_first", "Photos can only be sent with PULL_FROM_URL.", "photo_reference"))
        if len(urls) < 1 or len(urls) > P["max_images"]:
            issues.append(issue("photo_count", "fix_first", "A photo post takes 1 to %d images, not %d." % (P["max_images"], len(urls)), "photo_reference"))
        ci = p.get("cover_index")
        if not _is_int(ci) or ci < 0 or ci >= len(urls):
            issues.append(issue("photo_cover_index", "fix_first", "photo_cover_index must be between 0 and %d (it starts at 0)." % max(0, len(urls) - 1), "photo_reference"))
        for url in urls:
            _check_url(url, app, issues)
        for i, img in enumerate(images):
            fmt = _lower(img.get("format")).replace("jpg", "jpeg")
            if fmt not in P["formats"]:
                issues.append(issue("photo_format", "fix_first", "Image %d is %s; use JPEG or WebP." % (i + 1, _js(img.get("format"))), "media_transfer"))
            if _gt(img.get("size_bytes"), P["max_bytes_each"]):
                issues.append(issue("photo_too_large", "fix_first", "Image %d is over 20 MB." % (i + 1), "media_transfer"))
            iw, ih = img.get("width"), img.get("height")
            if _num(iw) and _num(ih) and (max(iw, ih) > 1920 or min(iw, ih) > 1080):
                issues.append(issue("photo_resolution", "review", "Image %d is %sx%s; TikTok's limit is \"1080p\", so resize it to 1920x1080 or less to be safe." % (i + 1, _js(iw), _js(ih)), "media_transfer"))
        desc = post.get("description")
        post_info = {"title": title, "description": "" if desc is None else desc}
        if direct:
            post_info.update({
                "privacy_level": level,
                "disable_comment": choices.get("allow_comment") is not True,
                "auto_add_music": choices.get("auto_add_music") is True,
                "brand_content_toggle": toggles["brand_content_toggle"],
                "brand_organic_toggle": toggles["brand_organic_toggle"],
            })
        body = {
            "post_info": post_info,
            "source_info": {"source": "PULL_FROM_URL", "photo_cover_index": ci if ci is not None else 0, "photo_images": urls},
            "post_mode": mode,
            "media_type": "PHOTO",
        }
        if choices.get("is_aigc") is True:
            body["is_aigc"] = True
        request = {"endpoint": RULES["endpoints"]["photo"], "body": body}

    out = {"id": pid, "creator": creator, "post_mode": mode, "media_type": typ, "status": _status_of(issues), "issues": issues, "request": request}
    if direct:
        out["ui_text"] = _ui_text(toggles)
    if plan:
        out["chunk_plan"] = plan
    return out


def _build_context(plan):
    app = plan.get("app") or {}
    posts = plan.get("posts") or []
    ctx = {"creator_rank": {}, "unaudited_over_cap": set(), "audited_over_cap": set(), "creator_post_count": {}, "pending_count": {}}
    seen = []
    for c in app.get("creators_posted_last_24h") or []:
        if c not in seen:
            seen.append(c)
    posted = dict(app.get("posts_last_24h_by_creator") or {})
    pending = dict(app.get("pending_inbox_last_24h_by_creator") or {})
    cap = app.get("active_creator_cap")
    for post in posts:
        mode = post.get("post_mode") or "DIRECT_POST"
        creator = post.get("creator")
        pid = post.get("id")
        if mode == "DIRECT_POST":
            if creator not in seen:
                seen.append(creator)
            rank = seen.index(creator) + 1
            ctx["creator_rank"][creator] = rank
            if rank > RULES["unaudited_client"]["max_users_posting_per_24h"]:
                ctx["unaudited_over_cap"].add(pid)
            if _is_int(cap) and rank > cap:
                ctx["audited_over_cap"].add(pid)
            n = posted.get(creator, 0) + 1
            posted[creator] = n
            ctx["creator_post_count"][pid] = n
        else:
            n = pending.get(creator, 0) + 1
            pending[creator] = n
            ctx["pending_count"][pid] = n
    return ctx


def check(plan):
    app = plan.get("app") or {}
    app_issues = []
    _check_screen(app, app_issues)
    ctx = _build_context(plan)
    posts = [_check_post(p, app, ctx) for p in plan.get("posts") or []]
    every = list(app_issues)
    for p in posts:
        every.extend(p["issues"])
    counts = {"fix_first": 0, "review": 0, "no_issues_found": 0}
    for p in posts:
        counts[p["status"]] += 1
    return {
        "checker": "tiktok-post-check",
        "rules_checked_on": RULES["checked_on"],
        "app": app.get("name"),
        "audited": app.get("audited") is True,
        "status": _status_of(every),
        "app_status": _status_of(app_issues),
        "app_issues": app_issues,
        "counts": counts,
        "posts": posts,
        "note": "A clean result is not TikTok's approval: it checks what you declare against the documented rules. TikTok's audit, moderation and caps still decide.",
    }


def _print_report(r):
    print("TikTok post check for %s (%s client, rules of %s)" % (r["app"] or "your app", "audited" if r["audited"] else "unaudited", r["rules_checked_on"]))
    print("Overall: %s" % r["status"])
    print("Export screen: %s" % r["app_status"])
    for i in r["app_issues"]:
        print("  [%s] %s: %s" % (i["severity"], i["code"], i["message"]))
    for p in r["posts"]:
        print("\n%s (%s, %s %s): %s" % (p["id"], p["creator"], p["post_mode"], p["media_type"], p["status"]))
        for i in p["issues"]:
            print("  [%s] %s: %s" % (i["severity"], i["code"], i["message"]))
        cp = p.get("chunk_plan")
        if cp and cp.get("valid"):
            print("  chunks: %d x %d bytes, final %d" % (cp["total_chunk_count"], cp["chunk_size"], cp["final_chunk_bytes"]))
    c = r["counts"]
    print("\nPosts: %d fix_first, %d review, %d no_issues_found" % (c["fix_first"], c["review"], c["no_issues_found"]))
    print(r["note"])


if __name__ == "__main__":
    if len(sys.argv) < 2:
        sys.stderr.write("Usage: python tiktok_post_check.py plan.json [--json]\n")
        sys.exit(2)
    with open(sys.argv[1], encoding="utf-8") as fh:
        report = check(json.load(fh))
    if "--json" in sys.argv:
        print(json.dumps(report, indent=2, ensure_ascii=False))
    else:
        _print_report(report)
    sys.exit(1 if report["status"] == "fix_first" else 0)
