#!/usr/bin/env python3
"""LinkedIn API post checker (APIWings, free to use, MIT licence).

Python twin of linkedin-post-check.mjs: same rules, same results, byte for byte.
Checks a plan of LinkedIn posts against LinkedIn's documented rules before you call the API
and prints the POST /rest/posts body it would send. It never calls LinkedIn.

Usage: python linkedin_post_check.py plan.json   (rules: linkedin-posting-rules.json in the same folder)
A clean result means "no documented rule broken", not "LinkedIn will accept it".
"""
import json
import re
import sys
from datetime import datetime, timezone
from pathlib import Path

HERE = Path(__file__).resolve().parent
RULES = json.loads((HERE / "linkedin-posting-rules.json").read_text(encoding="utf-8"))
DAY_MS = 86400000


def issue(code, severity, message, source):
    return {"code": code, "severity": severity, "message": message, "source": RULES["sources"].get(source, source)}


def _is_ascii_word(c):
    return c is not None and re.fullmatch(r"[A-Za-z0-9]", c) is not None


def _is_space(c):
    return c in (" ", "\t", "\n", "\r")


def _find_sub(arr, sub, start):
    n = len(sub)
    for i in range(start, len(arr) - n + 1):
        if arr[i:i + n] == sub:
            return i
    return -1


def escape_little(text):
    """Escape plain text for LinkedIn's little format: every reserved character gets a backslash."""
    return "".join("\\" + c if c in RULES["reserved_chars"] else c for c in text)


def _esc_char(arr, i, hashtags):
    c = arr[i]
    nxt = arr[i + 1] if i + 1 < len(arr) else None
    if c == "#" and hashtags and (i == 0 or _is_space(arr[i - 1])) and _is_ascii_word(nxt):
        return c, 0
    if c in RULES["reserved_chars"]:
        return "\\" + c, 1
    return c, 0


def build_little(raw, mentions=None, hashtags=True):
    """Build the little-format commentary from plain text, optional mentions and hashtags."""
    arr = list(raw)
    spans, errors, start = [], [], 0
    for m in mentions or []:
        sub = list(m.get("text") or "")
        at = _find_sub(arr, sub, start) if sub else -1
        if at < 0:
            errors.append(m.get("text") or "")
            continue
        spans.append((at, at + len(sub), m))
        start = at + len(sub)
    out, i, escaped = [], 0, 0
    for s_start, s_end, m in spans:
        while i < s_start:
            t, e = _esc_char(arr, i, hashtags)
            out.append(t)
            escaped += e
            i += 1
        out.append("@[" + escape_little(m["text"]) + "](" + str(m.get("urn")) + ")")
        i = s_end
    while i < len(arr):
        t, e = _esc_char(arr, i, hashtags)
        out.append(t)
        escaped += e
        i += 1
    return {"little": "".join(out), "escaped": escaped, "missingMentions": errors}


def _ms(s):
    try:
        d = datetime.fromisoformat(s)
    except (TypeError, ValueError):
        return None
    if d.tzinfo is None:
        d = d.replace(tzinfo=timezone.utc)
    return int(d.timestamp() * 1000)


def validate_little(text):
    """Validate text already in little format: reserved characters must be escaped unless part of a
    mention @[text](urn), a hashtag template {hashtag|#|tag} or a #word hashtag. Nothing is escaped again."""
    arr = list(text)
    unescaped, bad, mentions, i, n = [], [], 0, 0, len(arr)

    def read_until(start, close):
        j = start
        while j < n:
            if arr[j] == "\\" and j + 1 < n:
                j += 2
                continue
            if arr[j] == close:
                return j
            j += 1
        return -1

    while i < n:
        c = arr[i]
        if c == "\\" and i + 1 < n and arr[i + 1] in RULES["reserved_chars"]:
            i += 2
            continue
        if c == "@" and i + 1 < n and arr[i + 1] == "[":
            close = read_until(i + 2, "]")
            if close > 0 and close + 1 < n and arr[close + 1] == "(":
                end = read_until(close + 2, ")")
                if end > 0:
                    urn = "".join(arr[close + 2:end])
                    mentions += 1
                    if not re.fullmatch(r"urn:li:(person|organization):[A-Za-z0-9_-]+", urn):
                        bad.append("".join(arr[i + 2:close]))
                    i = end + 1
                    continue
        if c == "{":
            end = read_until(i + 1, "}")
            if "".join(arr[i:i + 9]) == "{hashtag|" and end > 0 and i + 10 < n and arr[i + 9] in ("#", "\uff03") and arr[i + 10] == "|":
                i = end + 1
                continue
        if c == "#" and (i == 0 or _is_space(arr[i - 1])) and _is_ascii_word(arr[i + 1] if i + 1 < n else None):
            i += 1
            continue
        if c in RULES["reserved_chars"]:
            unescaped.append({"char": c, "at": i})
        i += 1
    return {"little": text, "escaped": 0, "unescaped": unescaped, "badMentions": bad, "mentionCount": mentions, "missingMentions": []}


def _version_sunset(v):
    if v in RULES["version_sunsets"]:
        return RULES["version_sunsets"][v], False
    return f"{int(v[:4]) + 1}-{v[4:6]}-15", True


def _missing(x):
    return "missing" if x is None else str(x)


def check_app(app):
    out = []
    products = app.get("products") or []
    if "share_on_linkedin" not in products and "community_management" not in products:
        out.append(issue("NO_POSTING_PRODUCT", "error", "The app has neither Share on LinkedIn (w_member_social) nor the Community Management API (w_organization_social), so it cannot post.", "increasing_access"))
    if "community_management" in products and not app.get("community_management_tier"):
        out.append(issue("TIER_ASSUMED_DEVELOPMENT", "warning", "No Community Management tier given; assuming the Development tier (500 calls per app and 100 per member in 24 hours).", "increasing_access"))
    v = app.get("linkedin_version")
    review = _ms(str(app.get("review_date")) + "T00:00:00Z")
    if not v:
        out.append(issue("VERSION_MISSING", "error", "No Linkedin-Version header. LinkedIn does not apply the latest version by default and rejects the call (VERSION_MISSING).", "versioning"))
    elif not re.fullmatch(r"[0-9]{6}", str(v)):
        out.append(issue("VERSION_FORMAT", "error", f'Linkedin-Version "{v}" is not in YYYYMM format.', "versioning"))
    else:
        vs = str(v)
        if vs > RULES["latest_version"]:
            out.append(issue("VERSION_NOT_RELEASED", "warning", f"Version {vs} is newer than the latest version on the review date ({RULES['latest_version']}).", "versioning"))
        else:
            date, estimated = _version_sunset(vs)
            sun_ms = _ms(date + "T00:00:00Z")
            est = " (estimated: about 12 months after release)" if estimated else ""
            if review is not None and review >= sun_ms:
                out.append(issue("VERSION_SUNSET", "error", f"Version {vs} was sunset on {date}{est}. Calls return 426 NONEXISTENT_VERSION; move to {RULES['latest_version']}.", "migrations"))
            elif review is not None and sun_ms - review <= RULES["version_warning_days"] * DAY_MS:
                days = round((sun_ms - review) / DAY_MS)
                out.append(issue("VERSION_SUNSET_SOON", "warning", f"Version {vs} is sunset on {date}{est}, {days} days after the review date. Plan the move to {RULES['latest_version']}.", "migrations"))
    if not app.get("programmatic_refresh_tokens"):
        out.append(issue("RECONNECT_EVERY_60_DAYS", "info", "No programmatic refresh tokens: each member must authorize the app again before the 60-day access token expires.", "auth_code"))
    return out


def estimate_calls(content):
    """api_calls: requests to api.linkedin.com. file_uploads: PUTs to LinkedIn's upload URLs (reported apart)."""
    content = content or {}
    t = content.get("type") or "none"
    api, uploads = 1, 0
    if t in ("image", "multi_image"):
        n = len(content.get("images") or [])
        api += n
        uploads += n
    if t == "video":
        api += 2
        b = (content.get("video") or {}).get("bytes") or 0
        uploads += max(1, -(-b // RULES["video"]["upload_part_bytes"]))
    if t == "document":
        api += 1
        uploads += 1
    if t == "article" and (content.get("article") or {}).get("thumbnail_file"):
        api += 1
        uploads += 1
    return {"api_calls": api, "file_uploads": uploads, "http_requests": api + uploads}


def _check_images(images, out):
    r = RULES["image"]
    for n, img in enumerate(images):
        k = n + 1
        f = str(img.get("format") or "").upper()
        if f not in r["formats"]:
            out.append(issue("IMAGE_FORMAT", "error", f"Image {k}: format {img.get('format') or 'missing'} is not supported (JPG, PNG or GIF).", "images_api"))
        px = (img.get("width") or 0) * (img.get("height") or 0)
        if px >= r["max_pixels_exclusive"]:
            out.append(issue("IMAGE_PIXELS", "error", f"Image {k}: {img.get('width')}x{img.get('height')} is {px} pixels; LinkedIn needs fewer than {r['max_pixels_exclusive']}.", "images_api"))
        if f == "GIF" and (img.get("frames") or 1) > r["gif_max_frames"]:
            out.append(issue("GIF_FRAMES", "error", f"Image {k}: GIF with {img.get('frames')} frames; the maximum is {r['gif_max_frames']}.", "images_api"))
        alt = img.get("alt") or ""
        if not alt:
            out.append(issue("ALT_MISSING", "warning", f"Image {k}: no alt text. Optional for LinkedIn, but screen readers need it.", "images_api"))
        elif len(alt) > r["alt_max_chars"]:
            out.append(issue("ALT_TOO_LONG", "error", f"Image {k}: alt text has {len(alt)} characters; the maximum is {r['alt_max_chars']}.", "images_api"))
        elif len(alt) > r["alt_recommended_chars"]:
            out.append(issue("ALT_LONG", "warning", f"Image {k}: alt text has {len(alt)} characters; LinkedIn recommends fewer than {r['alt_recommended_chars']}.", "images_api"))


def _check_content(content, out):
    content = content or {}
    t = content.get("type") or "none"
    if t == "none":
        return
    if t == "image":
        n = len(content.get("images") or [])
        if n != 1:
            out.append(issue("IMAGE_COUNT", "error", f"A single-image post needs exactly 1 image (got {n}). Use multi_image for 2 to 20.", "posts_api"))
        _check_images(content.get("images") or [], out)
    elif t == "multi_image":
        n = len(content.get("images") or [])
        mi = RULES["multi_image"]
        if n < mi["min"] or n > mi["max"]:
            out.append(issue("MULTI_IMAGE_COUNT", "error", f"A multi-image post needs {mi['min']} to {mi['max']} images (got {n}).", "multi_image"))
        _check_images(content.get("images") or [], out)
    elif t == "video":
        v = content.get("video") or {}
        r = RULES["video"]
        if str(v.get("format") or "").upper() not in r["formats"]:
            out.append(issue("VIDEO_FORMAT", "error", f"Video format {v.get('format') or 'missing'} is not supported (MP4).", "videos_api"))
        sec = v.get("seconds")
        if not (sec is not None and r["min_seconds"] <= sec <= r["max_seconds"]):
            out.append(issue("VIDEO_DURATION", "error", f"Video length {_missing(sec)} s is outside 3 seconds to 30 minutes.", "videos_api"))
        b = v.get("bytes")
        if not (b is not None and b >= r["min_bytes"]):
            out.append(issue("VIDEO_TOO_SMALL", "error", f"Video file of {_missing(b)} bytes is under the 75 KB minimum.", "videos_api"))
        elif b > r["api_max_bytes"]:
            out.append(issue("VIDEO_TOO_LARGE", "error", f"Video file of {b} bytes is over the 5 GB upload maximum.", "videos_api"))
        elif b > r["spec_max_bytes"]:
            out.append(issue("VIDEO_SIZE_DISAGREE", "warning", f"Video file of {b} bytes: the upload field allows 5 GB, but the same page's file specification says 500 MB. Stay under 500 MB.", "videos_api"))
    elif t == "document":
        d = content.get("document") or {}
        r = RULES["document"]
        if str(d.get("format") or "").upper() not in r["formats"]:
            out.append(issue("DOCUMENT_FORMAT", "error", f"Document format {d.get('format') or 'missing'} is not supported (PDF, PPT, PPTX, DOC or DOCX).", "documents_api"))
        if d.get("bytes") is not None and d["bytes"] > r["max_bytes"]:
            out.append(issue("DOCUMENT_TOO_LARGE", "error", f"Document of {d['bytes']} bytes is over 100 MB.", "documents_api"))
        if d.get("pages") is not None and d["pages"] > r["max_pages"]:
            out.append(issue("DOCUMENT_PAGES", "error", f"Document has {d['pages']} pages; the maximum is {r['max_pages']}.", "documents_api"))
    elif t == "article":
        a = content.get("article") or {}
        if not a.get("source") or not str(a["source"]).startswith("https://"):
            out.append(issue("ARTICLE_SOURCE", "error", "An article post needs a source URL starting with https://.", "posts_api"))
        if not a.get("title"):
            out.append(issue("ARTICLE_TITLE", "error", "No article title. The Posts API does not scrape the URL, so the title must be sent in the post.", "posts_api"))
        if not a.get("thumbnail_file") and not a.get("thumbnail"):
            out.append(issue("ARTICLE_THUMBNAIL", "warning", "No article thumbnail. LinkedIn will not fetch one from the URL; upload an image and send its URN.", "posts_api"))
    elif t == "carousel":
        out.append(issue("CAROUSEL_SPONSORED_ONLY", "error", "Carousel posts are sponsored only; organic carousels are not supported. Use multi_image or a document.", "posts_api"))
    elif t == "poll":
        out.append(issue("POLL_NOT_CHECKED", "info", "Poll posts are organic only; this checker does not check poll fields.", "posts_api"))
    else:
        out.append(issue("CONTENT_TYPE", "error", f'Unknown content type "{t}".', "posts_api"))


def _build_body(post, little):
    c = post.get("content") or {"type": "none"}
    author = post.get("author")
    body = {
        "author": author.get("urn") if author else None,
        "commentary": little,
        "visibility": post.get("visibility") or None,
        "distribution": {"feedDistribution": "MAIN_FEED", "targetEntities": [], "thirdPartyDistributionChannels": []},
    }
    if post.get("targeting") is not None:
        body["distribution"]["targetEntities"] = [{"{facet}": ["{targeting URNs}"]}]

    def alt(img):
        return {"altText": img["alt"]} if img and img.get("alt") else {}

    t = c.get("type")
    images = c.get("images") or []
    if t == "image":
        body["content"] = {"media": {"id": "{image_urn_1}", **alt(images[0] if images else None)}}
    if t == "multi_image":
        body["content"] = {"multiImage": {"images": [{"id": f"{{image_urn_{n + 1}}}", **alt(img)} for n, img in enumerate(images)]}}
    if t == "video":
        body["content"] = {"media": {"title": (c.get("video") or {}).get("title") or "", "id": "{video_urn}"}}
    if t == "document":
        body["content"] = {"media": {"title": (c.get("document") or {}).get("title") or "", "id": "{document_urn}"}}
    if t == "article":
        a = c.get("article") or {}
        art = {"source": a.get("source") or "", "title": a.get("title") or ""}
        if a.get("description"):
            art["description"] = a["description"]
        if a.get("thumbnail_file") or a.get("thumbnail"):
            art["thumbnail"] = a.get("thumbnail") or "{image_urn_thumbnail}"
        body["content"] = {"article": art}
    body["lifecycleState"] = "PUBLISHED"
    body["isReshareDisabledByAuthor"] = False
    return body


def check_post(post, app):
    out = []
    products = app.get("products") or []
    a = post.get("author") or {}
    scopes = post.get("granted_scopes") or []
    atype = a.get("type")
    if atype not in ("person", "organization"):
        out.append(issue("AUTHOR_TYPE", "error", 'author.type must be "person" (member profile) or "organization" (company page).', "posts_api"))
    else:
        prefix = "urn:li:person:" if atype == "person" else "urn:li:organization:"
        if not a.get("urn") or not str(a["urn"]).startswith(prefix):
            out.append(issue("AUTHOR_URN", "error", f"A {atype} author needs a URN starting with {prefix}", "posts_api"))
        need = RULES["scopes"][atype]
        if need not in scopes:
            out.append(issue("SCOPE_MISSING", "error", f"Posting as a {atype} needs the {need} scope in the member's token.", "posts_api"))
        if atype == "organization":
            if "community_management" not in products:
                out.append(issue("ORG_NEEDS_COMMUNITY_MANAGEMENT", "error", "Company page posts need the Community Management API, a vetted product. Share on LinkedIn only posts to member profiles.", "increasing_access"))
            role = a.get("role")
            if role and role in RULES["role_aliases"]:
                out.append(issue("ROLE_ALIAS", "info", f"Role {role}: the Posts API page writes it this way, the roles page calls it {RULES['role_aliases'][role]}. Treated as the same role.", "org_roles"))
                role = RULES["role_aliases"][role]
            if not role:
                out.append(issue("ROLE_UNKNOWN", "warning", "Unknown page role. Ask organizationAuthorizations for ORGANIC_SHARE_CREATE (or read organizationAcls) before posting.", "org_authorizations"))
            elif role in RULES["organization_roles_check_first"]:
                out.append(issue("ROLE_CHECK_ORGANIC", "warning", f"Role {role}: the Posts API lists it for w_organization_social, but it is a sponsored content role and LinkedIn's authorization mapping gives ORGANIC_SHARE_CREATE only to ADMINISTRATOR and CONTENT ADMIN. Check ORGANIC_SHARE_CREATE with organizationAuthorizations.", "org_auth_mapping"))
            elif role not in RULES["organization_posting_roles"]:
                out.append(issue("ROLE_CANNOT_POST", "error", f"Role {role} cannot create organic page posts. Roles with ORGANIC_SHARE_CREATE: ADMINISTRATOR and CONTENT_ADMINISTRATOR.", "org_auth_mapping"))
    if post.get("lifecycle_state") and post["lifecycle_state"] != RULES["lifecycle_on_create"]:
        out.append(issue("LIFECYCLE_NOT_ALLOWED", "error", f"lifecycleState {post['lifecycle_state']} is not accepted on creation; only PUBLISHED. LinkedIn has no draft or scheduled state.", "post_schema"))
    vis = post.get("visibility")
    if not vis:
        out.append(issue("VISIBILITY_MISSING", "error", "visibility is required (PUBLIC, CONNECTIONS, LOGGED_IN or CONTAINER).", "post_schema"))
    elif vis not in RULES["visibility"]:
        out.append(issue("VISIBILITY_INVALID", "error", f"visibility {vis} is not a LinkedIn value.", "post_schema"))
    elif atype == "organization" and vis == "CONNECTIONS":
        out.append(issue("ORG_CONNECTIONS_VISIBILITY", "warning", "CONNECTIONS means the owner's 1st-degree network; a company page has followers, not connections. Use PUBLIC.", "post_schema"))

    little = ""
    content_type = (post.get("content") or {}).get("type") or "none"
    commentary = post.get("commentary")
    mentions = post.get("mentions") or []
    if not isinstance(commentary, str):
        out.append(issue("COMMENTARY_MISSING", "error", "commentary is a required field (it can be an empty string when the post has media).", "post_schema"))
    else:
        little_mode = post.get("commentary_format") == "little"
        b = validate_little(commentary) if little_mode else build_little(commentary, mentions, post.get("hashtags") is not False)
        if little_mode:
            for u in b["unescaped"]:
                out.append(issue("UNESCAPED_RESERVED", "error", f'commentary_format is "little" but "{u["char"]}" at position {u["at"]} is not escaped and is not part of a mention or hashtag.', "little_text"))
            for m in b["badMentions"]:
                out.append(issue("MENTION_URN", "error", f'Mention "{m}" needs a person or organization URN.', "little_text"))
        elif re.search(r"\\[|{}@\[\]()<>#\\*_~]", commentary):
            out.append(issue("POSSIBLY_ALREADY_ESCAPED", "warning", 'The text already contains backslash escapes. The checker escapes plain text, so they would be escaped twice. If the text is already in little format, set commentary_format to "little".', "little_text"))
        little = b["little"]
        for m in b["missingMentions"]:
            out.append(issue("MENTION_TEXT_NOT_FOUND", "error", f'Mention text "{m}" is not in the commentary.', "little_text"))
        for m in ([] if little_mode else mentions):
            if not re.fullmatch(r"urn:li:(person|organization):[A-Za-z0-9_-]+", m.get("urn") or ""):
                out.append(issue("MENTION_URN", "error", f'Mention "{m.get("text")}" needs a person or organization URN.', "little_text"))
        if mentions or b.get("mentionCount", 0) > 0:
            out.append(issue("MENTION_NAME_MATCH", "info", "A mention links only if its text matches the member or organization name (case sensitive; organizations need the full name). Otherwise it shows as plain text.", "posts_api"))
        if commentary == "" and content_type == "none":
            out.append(issue("EMPTY_POST", "error", "The post has no text and no content.", "post_schema"))
        visible = re.sub(r"\\([|{}@\[\]()<>#\\*_~])", r"\1", commentary) if little_mode else commentary
        raw_len, lit_len, mx = len(visible), len(little), RULES["commentary_max_chars"]
        if raw_len > mx:
            out.append(issue("TEXT_TOO_LONG", "error", f"The text has {raw_len} characters; LinkedIn posts allow {mx}.", "help_post_length"))
        elif lit_len > mx:
            out.append(issue("TEXT_TOO_LONG_ESCAPED", "warning", f"The text has {raw_len} characters, but {lit_len} after escaping. LinkedIn does not say which one it counts; keep the escaped text under {mx}.", "little_text"))
        if b["escaped"] > 0:
            out.append(issue("RESERVED_ESCAPED", "info", f"{b['escaped']} reserved character(s) escaped with a backslash. LinkedIn requires it for them to be treated as plain text.", "little_text"))
    _check_content(post.get("content"), out)

    tg = post.get("targeting")
    if tg is not None:
        if atype != "organization":
            out.append(issue("TARGETING_ORG_ONLY", "error", "Targeted organic posts are for company pages only.", "posts_api"))
        elif tg.get("audience_estimate") is None:
            out.append(issue("TARGETING_NO_ESTIMATE", "warning", "No audience estimate. Check it with the Audience Counts API: it must be more than 300 members.", "posts_api"))
        elif tg["audience_estimate"] <= RULES["targeting_min_audience_exclusive"]:
            out.append(issue("TARGETING_AUDIENCE_TOO_SMALL", "error", f"Target audience of {tg['audience_estimate']}: LinkedIn needs more than 300 members.", "posts_api"))

    review_start = _ms(str(app.get("review_date")) + "T00:00:00Z")
    pub = _ms(post["publish_at"]) if post.get("publish_at") else review_start
    exp = _ms(post["token_expires_at"]) if post.get("token_expires_at") else None
    if exp is not None and pub is not None:
        if exp <= pub:
            out.append(issue("TOKEN_EXPIRES_BEFORE_PUBLISH", "error", f"The member's token expires ({post['token_expires_at']}) before the publish time. Ask them to reconnect now.", "auth_code"))
        elif exp - pub < RULES["token"]["warn_days"] * DAY_MS:
            out.append(issue("TOKEN_EXPIRES_SOON", "warning", "The member's token expires less than 7 days after the publish time. Ask them to reconnect.", "auth_code"))
    if post.get("publish_at") and review_start is not None and (_ms(post["publish_at"]) or 0) >= review_start + DAY_MS:
        out.append(issue("SCHEDULED_IN_YOUR_QUEUE", "info", "LinkedIn has no scheduled state: your own queue must create the post at the publish time.", "post_schema"))
    origin = post.get("origin") or {}
    if origin.get("generated_by") in ("automation", "ai_agent") and not origin.get("approved_by"):
        out.append(issue("AUTOMATED_WITHOUT_APPROVAL", "warning", "Generated by software with no person approving it. LinkedIn's API Terms (3.1) forbid using the APIs \"to automate posting\". A person approving each post is good practice, not a guarantee of compliance.", "api_terms"))
    if post.get("verify_by_reading") and atype == "person" and RULES["scopes"]["read_member_posts"] not in scopes:
        out.append(issue("READ_BACK_CLOSED", "warning", "Reading member posts back needs r_member_social, which LinkedIn is not granting. Keep the post URN from the x-restli-id header instead.", "posts_api"))
    return {"issues": out, "body": _build_body(post, little), "calls": estimate_calls(post.get("content"))}


def _status(issues):
    if any(i["severity"] == "error" for i in issues):
        return "blocked"
    if any(i["severity"] == "warning" for i in issues):
        return "warnings"
    return "no_issues_found"


def check_plan(plan):
    app = plan.get("app") or {}
    app_issues = check_app(app)
    products = app.get("products") or []
    dev = "community_management" in products and (app.get("community_management_tier") or "development") == "development"
    limits = RULES["daily_limits"]["community_management_development" if dev else "share_on_linkedin"]
    posts, per_member, per_app = [], {}, {}
    for p in plan.get("posts") or []:
        r = check_post(p, app)
        day = (p.get("publish_at") or app.get("review_date") or "")[:10]
        member = p.get("member_urn") or (p.get("author") or {}).get("urn") or "unknown"
        key = day + " " + member
        per_member[key] = per_member.get(key, 0) + r["calls"]["api_calls"]
        per_app[day] = per_app.get(day, 0) + r["calls"]["api_calls"]
        posts.append({
            "id": p.get("id"),
            "status": _status(r["issues"]),
            "issues": r["issues"],
            "estimated_requests": r["calls"],
            "request": {
                "method": "POST",
                "url": "https://api.linkedin.com/rest/posts",
                "headers": {"Linkedin-Version": str(app.get("linkedin_version") or ""), "X-Restli-Protocol-Version": "2.0.0", "Content-Type": "application/json"},
                "body": r["body"],
            },
        })
    tier = "Community Management Development tier" if dev else "Share on LinkedIn"
    src = "increasing_access" if dev else "share_on_linkedin"
    for k in sorted(per_member):
        if per_member[k] > limits["member"]:
            day, member = k.split(" ")
            app_issues.append(issue("MEMBER_DAILY_CALLS", "warning", f"{member} needs about {per_member[k]} API calls on {day} (UTC), not counting file uploads; the {tier} documents {limits['member']} per member a day.", src))
    for day in sorted(per_app):
        if per_app[day] > limits["app"]:
            app_issues.append(issue("APP_DAILY_CALLS", "warning", f"The app needs about {per_app[day]} API calls on {day} (UTC), not counting file uploads; the {tier} documents {limits['app']} per app a day.", src))
    counts = {"no_issues_found": 0, "warnings": 0, "blocked": 0}
    for p in posts:
        counts[p["status"]] += 1
    return {"checker": "linkedin-post-check 1.1", "rules_reviewed": RULES["reviewed"], "app": {"status": _status(app_issues), "issues": app_issues}, "summary": counts, "posts": posts}


def to_json(result):
    return json.dumps(result, indent=2, ensure_ascii=False)


if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Usage: python linkedin_post_check.py plan.json", file=sys.stderr)
        sys.exit(2)
    res = check_plan(json.loads(Path(sys.argv[1]).read_text(encoding="utf-8")))
    sys.stdout.write(to_json(res) + "\n")
    sys.exit(1 if res["app"]["status"] == "blocked" or res["summary"]["blocked"] else 0)
