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

Checks a plan of YouTube uploads against Google's and YouTube's documented rules before you call the API:
scopes and OAuth status, the two daily quota buckets (per Pacific Time day), file size and length,
Shorts, title, description, tags, privacy and scheduling, audience and disclosures, thumbnails,
playlists, refresh tokens in Testing mode and the user's consent. It also prints the resumable
upload request it would send. It never calls YouTube. Same results as youtube-upload-check.mjs.

Usage: python youtube_upload_check.py plan.json   (rules: youtube-upload-rules.json in the same folder)
A clean result means "no documented rule broken", not "YouTube will accept the video".
"""
import json
import re
import sys
from datetime import datetime, timedelta, timezone
from pathlib import Path

HERE = Path(__file__).resolve().parent
RULES = json.loads((HERE / "youtube-upload-rules.json").read_text(encoding="utf-8"))
DAY_MS = 86400000
SCOPE_PREFIX = "https://www.googleapis.com/auth/"
TIME_RE = re.compile(r"([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2})(?::([0-9]{2})(?:\.([0-9]{1,6}))?)?(Z|[+-][0-9]{2}:[0-9]{2})")
EPOCH = datetime(1970, 1, 1, tzinfo=timezone.utc)


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


def fmt(n):
    """12345 -> "12,345" (same output as the JavaScript version)."""
    return f"{int(n):,}"


def is_num(x):
    return isinstance(x, (int, float)) and not isinstance(x, bool)


def full_scope(s):
    return s if s.startswith("https://") else SCOPE_PREFIX + s


def has_any(scopes, lst):
    return any(s in lst for s in scopes)


def _utc_ms(y, mo, d, h=0, mi=0, se=0):
    return int((datetime(y, mo, d, h, mi, se, tzinfo=timezone.utc) - EPOCH).total_seconds()) * 1000


def parse_time(s):
    """Strict ISO 8601 date-time with Z or an offset. Returns milliseconds or None."""
    if not isinstance(s, str):
        return None
    m = TIME_RE.fullmatch(s)
    if not m:
        return None
    y, mo, d, h, mi = (int(m.group(i)) for i in range(1, 6))
    se = int(m.group(6) or 0)
    if mo < 1 or mo > 12 or d < 1 or h > 23 or mi > 59 or se > 59:
        return None
    leap = (y % 4 == 0 and y % 100 != 0) or y % 400 == 0
    dim = [31, 29 if leap else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][mo - 1]
    if d > dim:
        return None
    off = 0
    z = m.group(8)
    if z != "Z":
        sign = -1 if z[0] == "-" else 1
        oh, om = int(z[1:3]), int(z[4:6])
        if oh > 23 or om > 59:
            return None
        off = sign * (oh * 60 + om) * 60000
    return _utc_ms(y, mo, d, h, mi, se) - off


def _nth_sunday(y, month, n):
    first = (datetime(y, month, 1).weekday() + 1) % 7  # Sunday = 0, as in JavaScript
    return 1 + ((7 - first) % 7) + 7 * (n - 1)


def pacific_day(ms):
    """YouTube's quota day (midnight Pacific Time), with US daylight saving rules. No time zone library needed."""
    y = (EPOCH + timedelta(milliseconds=ms)).year
    start = _utc_ms(y, 3, _nth_sunday(y, 3, 2), 10)
    end = _utc_ms(y, 11, _nth_sunday(y, 11, 1), 9)
    offset_h = -7 if start <= ms < end else -8
    return (EPOCH + timedelta(milliseconds=ms + offset_h * 3600000)).date().isoformat()


def tags_length(tags):
    """Length of snippet.tags as YouTube counts it: commas count, and a tag with a space counts with quotes."""
    n = max(0, len(tags) - 1)
    for t in tags:
        n += len(t) + (2 if " " in t else 0)
    return n


def expected_format(video):
    """"short", "long" or "unknown": YouTube makes a square or vertical video of up to 3 minutes a Short."""
    if not video or not video.get("width") or not video.get("height") or video.get("seconds") is None:
        return "unknown"
    return "short" if video["height"] >= video["width"] and video["seconds"] <= RULES["shorts"]["max_seconds"] else "long"


def mime_accepted(mime):
    return isinstance(mime, str) and (re.fullmatch(r"video/([a-z0-9.+-]+|\*)", mime, re.I | re.A) is not None or mime == "application/octet-stream")


def estimate_requests(up, app=None):
    v = up.get("video") or {}
    chunk = up.get("upload_chunk_bytes")
    puts = -(-v["bytes"] // chunk) if chunk and v.get("bytes") else 1
    thumb = 1 if up.get("thumbnail") else 0
    playlist = 1 if up.get("playlist_id") else 0
    checks = 1 if (up.get("confirm_processing") or (thumb and expected_format(v) == "short")) else 0
    uc = RULES["unit_costs"]
    units = thumb * uc["thumbnails.set"] + playlist * uc["playlistItems.insert"] + checks * uc["videos.list"]
    return {"videos_insert_calls": 1, "other_quota_units": units, "status_checks": checks,
            "upload_requests": int(puts), "http_requests": int(1 + puts + thumb + playlist + checks)}


def build_request(up):
    res = up.get("resource") or {}
    parts = [k for k in res if k in ("snippet", "status", "localizations", "paidProductPlacementDetails", "recordingDetails")]
    v = up.get("video") or {}
    q = "uploadType=resumable&part=" + ",".join(parts) + ("&notifySubscribers=false" if up.get("notify_subscribers") is False else "")
    return {"method": "POST", "url": "https://www.googleapis.com/upload/youtube/v3/videos?" + q,
            "headers": {"Content-Type": "application/json; charset=UTF-8",
                        "X-Upload-Content-Length": str(v.get("bytes") or 0),
                        "X-Upload-Content-Type": v.get("mime") or "application/octet-stream"},
            "body": res}


def check_app(app):
    out = []
    scopes = [full_scope(s) for s in app.get("requested_scopes") or []]
    features = ["upload"] if app.get("features") is None else app["features"]
    oauth = app.get("oauth") or {}
    sc = RULES["scopes"]
    if not has_any(scopes, sc["upload"]):
        out.append(issue("NO_UPLOAD_SCOPE", "error", "None of the requested scopes allows videos.insert. Request youtube.upload (the narrowest one that uploads).", "videos_insert"))
    only_uploads = all(f in ("upload", "thumbnails") for f in features)
    broad = [s for s in scopes if s in sc["broad"]]
    if only_uploads and broad:
        names = " and ".join(s[len(SCOPE_PREFIX):] for s in broad)
        out.append(issue("BROADER_SCOPE_THAN_NEEDED", "warning", f"Your app only uploads videos and thumbnails but requests {names}, which also allow deleting videos. YouTube's Developer Policies ask for the narrowest scope; youtube.upload covers both.", "developer_policies"))
    if "playlists" in features and not has_any(scopes, sc["playlist_items"]):
        out.append(issue("PLAYLIST_SCOPE_MISSING", "error", "playlistItems.insert needs youtube, youtube.force-ssl or youtubepartner; youtube.upload is not enough.", "playlist_items_insert"))
    if "read_status" in features and not has_any(scopes, sc["read_own_video"]):
        out.append(issue("STATUS_CHECK_SCOPE_MISSING", "warning", "Checking processing with videos.list needs the owner's authorization; youtube.upload is not listed for reading. Add youtube.readonly (our reading).", "videos_list"))
    external = (oauth.get("user_type") or "external") == "external"
    if external and oauth.get("publishing_status") == "testing":
        out.append(issue("TESTING_MODE", "warning", f"The OAuth consent screen is in Testing: only listed test users can connect, and their refresh tokens expire after {RULES['testing_refresh_token_days']} days.", "oauth_refresh_expiry"))
    if external and oauth.get("publishing_status") == "in_production" and oauth.get("verification") != "verified":
        out.append(issue("UNVERIFIED_APP", "warning", f"In production without Google's OAuth verification for sensitive scopes: users see the unverified app screen and the app is limited to {RULES['unverified_new_user_cap']} new users.", "unverified_apps"))
    if (app.get("ui") or {}).get("privacy_choice_shown") is False:
        out.append(issue("PRIVACY_CHOICE_NOT_SHOWN", "error", "YouTube's Developer Policies require apps that upload to show an option to choose public, private or unlisted.", "developer_policies"))
    if (app.get("ui") or {}).get("upload_notice_shown") is False:
        out.append(issue("UPLOAD_NOTICE_MISSING", "error", "The screen with the upload button must show YouTube's required notice (\"By clicking 'upload,' you certify that...\") with the link to YouTube's Terms of Service (API Terms, section 9.1).", "api_tos"))
    return out


def check_upload(up, app):
    out = []
    oauth = app.get("oauth") or {}
    v = up.get("video")
    res = up.get("resource") or {}
    sn = res.get("snippet") or {}
    st = res.get("status") or {}
    ch = up.get("channel") or {}
    upload_ms = parse_time(up.get("upload_at"))
    # The file
    if not v or not v.get("bytes"):
        out.append(issue("MEDIA_BODY_REQUIRED", "error", "No video file: videos.insert returns mediaBodyRequired without the video content.", "errors"))
    else:
        if not mime_accepted(v.get("mime")):
            out.append(issue("VIDEO_TYPE_NOT_ACCEPTED", "error", f"MIME type {v.get('mime') or '(none)'} is not accepted; videos.insert takes video/* or application/octet-stream.", "videos_insert"))
        if v["bytes"] > RULES["video"]["max_bytes"]:
            out.append(issue("VIDEO_TOO_LARGE", "error", f"The file has {fmt(v['bytes'])} bytes; the maximum is 256 GB.", "videos_insert"))
    if v and v.get("seconds") is not None:
        if v["seconds"] > RULES["video"]["max_seconds"]:
            out.append(issue("VIDEO_TOO_LONG", "error", f"The video lasts {fmt(v['seconds'])} seconds; YouTube takes up to 12 hours (43,200 seconds).", "help_long_videos"))
        elif v["seconds"] > RULES["video"]["unverified_max_seconds"]:
            if ch.get("verified") is False:
                out.append(issue("LONG_VIDEO_UNVERIFIED_CHANNEL", "error", "The video is longer than 15 minutes and the channel's account is not verified; YouTube only allows longer videos from verified accounts.", "help_long_videos"))
            elif ch.get("verified") is not True:
                out.append(issue("LONG_VIDEO_CHECK_CHANNEL", "warning", "The video is longer than 15 minutes: check that the channel's account is verified, or the upload fails.", "help_long_videos"))
    fmt_kind = expected_format(v)
    if up.get("intended_format") == "short" and fmt_kind == "long":
        out.append(issue("NOT_A_SHORT", "warning", "Planned as a Short, but YouTube only makes square or vertical videos of up to 3 minutes Shorts. There is no Shorts flag in the API.", "help_shorts"))
    if up.get("intended_format") == "long" and fmt_kind == "short":
        out.append(issue("WILL_BE_A_SHORT", "warning", "Planned as a regular video, but it is square or vertical and up to 3 minutes long, so YouTube will treat it as a Short.", "help_shorts"))
    chunk = up.get("upload_chunk_bytes")
    if chunk and chunk % RULES["chunk_multiple_bytes"] != 0:
        out.append(issue("CHUNK_SIZE_INVALID", "error", f"Chunks of {fmt(chunk)} bytes: every chunk but the last must be a multiple of 256 KB (262,144 bytes).", "resumable"))
    # Metadata
    title = sn.get("title")
    if not isinstance(title, str) or title.strip() == "":
        out.append(issue("TITLE_MISSING", "error", "No title: videos.insert returns invalidTitle for an empty title.", "errors"))
    else:
        if len(title) > RULES["title"]["max_chars"]:
            out.append(issue("TITLE_TOO_LONG", "error", f"The title has {len(title)} characters; the maximum is 100.", "videos_resource"))
        if re.search(r"[<>]", title):
            out.append(issue("TITLE_ANGLE_BRACKETS", "error", "The title contains < or >, which YouTube does not allow.", "videos_resource"))
    desc = sn.get("description")
    if isinstance(desc, str):
        b = len(desc.encode("utf-8"))
        if b > RULES["description"]["max_bytes"]:
            out.append(issue("DESCRIPTION_TOO_LONG", "error", f"The description has {fmt(b)} bytes in UTF-8; the maximum is 5,000 bytes (accents and emoji take more than one).", "videos_resource"))
        if re.search(r"[<>]", desc):
            out.append(issue("DESCRIPTION_ANGLE_BRACKETS", "error", "The description contains < or >, which YouTube does not allow.", "videos_resource"))
    tags = sn.get("tags")
    if isinstance(tags, list):
        if any(not isinstance(t, str) or t.strip() == "" for t in tags):
            out.append(issue("TAG_EMPTY", "error", "An empty tag: YouTube's samples note a 400 Bad Request for empty tags. Remove it.", "videos_insert"))
        n = tags_length([t for t in tags if isinstance(t, str)])
        if n > RULES["tags"]["max_chars"]:
            out.append(issue("TAGS_TOO_LONG", "error", f"The tags count as {n} characters (commas included, and quotes around tags with spaces); the maximum is 500.", "videos_resource"))
    cat = sn.get("categoryId")
    if cat is not None and not (isinstance(cat, str) and re.fullmatch(r"[0-9]+", cat)):
        out.append(issue("CATEGORY_ID_FORMAT", "error", 'categoryId must be a category ID as a string of digits (for example "22"); get valid IDs with videoCategories.list.', "videos_resource"))
    if res.get("localizations") and not sn.get("defaultLanguage"):
        out.append(issue("DEFAULT_LANGUAGE_NOT_SET", "error", "Localized titles or descriptions need snippet.defaultLanguage, or videos.insert returns defaultLanguageNotSet.", "errors"))
    # Privacy and scheduling
    ps = st.get("privacyStatus")
    if ps is None:
        out.append(issue("PRIVACY_NOT_SET", "warning", "No privacyStatus: the video defaults to public (some accounts default to private). Let the user choose, as the Developer Policies require.", "videos_insert"))
    elif ps not in RULES["privacy_status"]:
        out.append(issue("PRIVACY_INVALID", "error", f'privacyStatus "{ps}" is not one of private, public or unlisted.', "videos_resource"))
    if st.get("publishAt") is not None:
        pub = parse_time(st["publishAt"])
        if pub is None:
            out.append(issue("PUBLISH_AT_INVALID", "error", "publishAt is not an ISO 8601 date and time with a time zone (for example 2026-12-05T17:00:00Z).", "videos_resource"))
        else:
            if ps != "private":
                out.append(issue("PUBLISH_AT_NEEDS_PRIVATE", "error", "publishAt can only be set when privacyStatus is private; YouTube makes the video public at that time.", "videos_resource"))
            if upload_ms is not None and pub <= upload_ms:
                out.append(issue("PUBLISH_AT_IN_PAST", "warning", "publishAt is not after the upload time: YouTube publishes the video right away.", "videos_resource"))
    if st.get("selfDeclaredMadeForKids") is None:
        out.append(issue("MADE_FOR_KIDS_NOT_SET", "warning", "selfDeclaredMadeForKids is not set: ask the user whether the video is made for kids and send true or false (our reading).", "videos_resource"))
    origin = up.get("origin") or {}
    if origin.get("realistic_synthetic") is True and st.get("containsSyntheticMedia") is not True:
        out.append(issue("SYNTHETIC_NOT_DISCLOSED", "error", "The video has realistic altered or synthetic content but containsSyntheticMedia is not true.", "videos_resource"))
    ppd = res.get("paidProductPlacementDetails") or {}
    if not isinstance(ppd.get("hasPaidProductPlacement"), bool):
        out.append(issue("PAID_PLACEMENT_NOT_DECLARED", "warning", "hasPaidProductPlacement is not set. Since 16 November 2026 it no longer defaults to false: send true or false.", "revision_history"))
    # Consent
    if origin.get("generated_by") and origin.get("generated_by") != "person" and not origin.get("approved_by"):
        out.append(issue("UPLOAD_WITHOUT_EXPRESS_CONSENT", "error", "Generated or triggered by software with no person approving it. The Developer Policies forbid automating uploads without the user's prior specific and express consent.", "developer_policies"))
    # Tokens
    if (oauth.get("user_type") or "external") == "external" and oauth.get("publishing_status") == "testing" and up.get("refresh_token_issued_at"):
        issued = parse_time(up["refresh_token_issued_at"])
        if issued is not None and upload_ms is not None and upload_ms >= issued + RULES["testing_refresh_token_days"] * DAY_MS:
            out.append(issue("REFRESH_TOKEN_EXPIRED", "error", "In Testing mode the refresh token expires 7 days after it was issued, before this upload. The user must connect again.", "oauth_refresh_expiry"))
    # Thumbnail
    th = up.get("thumbnail")
    if th:
        f = str(th.get("format") or "").lower()
        if f not in RULES["thumbnail"]["formats"]:
            out.append(issue("THUMBNAIL_FORMAT", "error", f"Thumbnail format {th.get('format') or '(none)'}: thumbnails.set takes JPEG or PNG.", "thumbnails_set"))
        if is_num(th.get("bytes")) and th["bytes"] > RULES["thumbnail"]["max_bytes"]:
            out.append(issue("THUMBNAIL_TOO_LARGE", "error", f"The thumbnail has {fmt(th['bytes'])} bytes; the maximum is 50 MB.", "thumbnails_set"))
        if fmt_kind == "short":
            small = is_num(th.get("height")) and th["height"] < RULES["thumbnail"]["min_height_shorts"]
        else:
            small = is_num(th.get("width")) and th["width"] < RULES["thumbnail"]["min_width"]
        if small:
            msg = "YouTube Help asks for a Shorts thumbnail at least 640 pixels high." if fmt_kind == "short" else "YouTube Help asks for a thumbnail at least 640 pixels wide."
            out.append(issue("THUMBNAIL_SMALL", "warning", msg, "help_thumbnails"))
        if ch.get("verified") is not True:
            out.append(issue("THUMBNAIL_NEEDS_VERIFIED_ACCOUNT", "error" if ch.get("verified") is False else "warning", "Custom thumbnails need a verified YouTube account; otherwise thumbnails.set returns forbidden.", "help_thumbnails"))
    return out


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)
    quota = dict(RULES["default_quota"], **(app.get("quota") or {}))
    inserts, units, uploads = {}, {}, []
    for up in plan.get("uploads") or []:
        issues = check_upload(up, app)
        est = estimate_requests(up, app)
        ms = parse_time(up.get("upload_at"))
        if up.get("upload_at") is not None and ms is None:
            issues.append(issue("UPLOAD_AT_INVALID", "error", "upload_at is not an ISO 8601 date and time with a time zone.", "our_reading"))
        day = "unknown day" if ms is None else pacific_day(ms)
        inserts[day] = inserts.get(day, 0) + est["videos_insert_calls"]
        units[day] = units.get(day, 0) + est["other_quota_units"]
        uploads.append({"id": up.get("id"), "status": status(issues), "expected_format": expected_format(up.get("video")),
                        "quota_day_pacific": day, "issues": issues, "estimated_requests": est, "request": build_request(up)})
    for day in sorted(inserts):
        if inserts[day] > quota["videos_insert_per_day"]:
            app_issues.append(issue("INSERT_QUOTA_EXCEEDED", "error", f"{inserts[day]} uploads on {day} (Pacific Time) for a videos.insert quota of {fmt(quota['videos_insert_per_day'])} a day. Every channel that uses your project shares it.", "quota"))
        if units[day] > quota["other_units_per_day"]:
            app_issues.append(issue("UNITS_QUOTA_EXCEEDED", "error", f"{fmt(units[day])} units of thumbnails, playlists and status checks on {day} (Pacific Time) for {fmt(quota['other_units_per_day'])} a day.", "quota"))
    counts = {"no_issues_found": 0, "warnings": 0, "blocked": 0}
    for u in uploads:
        counts[u["status"]] += 1
    return {"checker": "youtube-upload-check 1.0", "rules_reviewed": RULES["reviewed"],
            "app": {"status": status(app_issues), "issues": app_issues,
                    "quota_used": [{"day_pacific": d, "videos_insert_calls": inserts[d], "other_quota_units": units[d]} for d in sorted(inserts)]},
            "summary": counts, "uploads": uploads}


if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Usage: python youtube_upload_check.py plan.json", file=sys.stderr)
        sys.exit(2)
    result = check_plan(json.loads(Path(sys.argv[1]).read_text(encoding="utf-8")))
    print(json.dumps(result, indent=2, ensure_ascii=False))
    sys.exit(1 if result["app"]["status"] == "blocked" or result["summary"]["blocked"] else 0)
