#!/usr/bin/env python3
"""Compare what YouTube transcript APIs cost at your monthly volume.

Standard library only (Python 3.9+), no network calls. Prices are list prices
from each vendor's own pricing page, checked on November 20, 2026 (ours on
November 23, when we added a founding price for new accounts). They change,
so check the pages before you buy, and edit PROVIDERS below if one moved.

Examples:
  python transcript_api_costs.py --per-month 10000
  python transcript_api_costs.py --per-month 50000 --no-captions 0.12
  python transcript_api_costs.py --per-month 3000 --json

What it models:
  * the cheapest published plan (or pack) that covers your volume
  * whether a video without captions is billed ("misses"): yes, no, or not stated
  * whether unused credits expire at the end of the month
It doesn't model taxes, yearly discounts a vendor doesn't publish, or support.
"""
import argparse
import json
import math
import sys

CHECKED = "2026-11-20"


def plan_cost(plans, n):
    """Cheapest monthly plan covering n requests. plans: [(price, included)]. None if none fits."""
    fits = [p for p, inc in plans if inc >= n]
    return min(fits) if fits else None


# YouTubeTranscriptAPI has two price tiers. Founding: subscribe within 7 days of
# signing up and keep $3/month or $30/year while subscribed. Standard, after
# that: $7/month or $60/year. Same credits and top-up prices on both.
def ytt_monthly(n, price=3):
    # 1,000 credits a month; top-ups $2.50 per 1K (bought 5K at a time, never expire).
    return price + math.ceil(max(0, n - 1000) / 1000) * 2.50


def ytt_annual(n, price=30):
    # 15,000 credits a year up front; top-ups $2 per 1K. Shown per month.
    return (price + math.ceil(max(0, n * 12 - 15000) / 1000) * 2.00) / 12


def ytt_monthly_standard(n):
    return ytt_monthly(n, 7)


def ytt_annual_standard(n):
    return ytt_annual(n, 60)


def supadata(n):
    # (price a month, credits, recharge $ per pack, credits per pack). Basic is $60/year.
    best = None
    for price, inc, r_price, r_size in [(0, 100, None, None), (5, 300, 10, 1000), (17, 3000, 10, 1000),
                                        (47, 30000, 10, 5000), (297, 300000, 20, 20000), (897, 1000000, 20, 20000)]:
        extra = max(0, n - inc)
        if extra and not r_price:
            continue
        cost = price + (math.ceil(extra / r_size) * r_price if extra else 0)
        best = cost if best is None else min(best, cost)
    return best


def scrapecreators(n):
    # Pay as you go, credits never expire: $47 for 25,000 or $497 for 500,000.
    # Spread over the months a pack lasts; use the big pack if a year needs it.
    rate = 0.994 if n * 12 >= 500000 else 1.88
    return n * rate / 1000


def socialkit(n):
    # Billed annually (the published rates); credits refresh monthly, no roll-over.
    return plan_cost([(0, 20), (29, 12000), (39, 18000), (95, 50000), (210, 150000)], n)


def youtube_transcript_io(n):
    return plan_cost([(0, 25), (9.99, 1000), (24.99, 3000), (47.99, 6000), (79.99, 10000)], n)


def searchapi(n):
    return plan_cost([(40, 10000), (100, 35000), (250, 100000), (500, 250000), (900, 500000),
                      (1500, 1000000)], n)


def serpapi(n):
    return plan_cost([(0, 250), (25, 1000), (75, 5000), (150, 15000), (275, 30000)], n)


def scrapingdog(n):
    # The YouTube Transcript API costs 5 credits a request; plans listed by requests.
    return plan_cost([(40, 40000), (90, 200000), (200, 600000)], n)


def apify_cheapest(n):
    # Cheapest transcript Actor we found on the Apify Store: from $0.70 per 1,000.
    return n * 0.70 / 1000


# name, function, misses billed?, credits expire monthly?, what it covers
PROVIDERS = [
    ("YouTubeTranscriptAPI (Annual, founding)", ytt_annual, "no", "no (roll over)", "YouTube"),
    ("YouTubeTranscriptAPI (Monthly, founding)", ytt_monthly, "no", "no (roll over)", "YouTube"),
    ("YouTubeTranscriptAPI (Annual, standard)", ytt_annual_standard, "no", "no (roll over)", "YouTube"),
    ("YouTubeTranscriptAPI (Monthly, standard)", ytt_monthly_standard, "no", "no (roll over)", "YouTube"),
    ("Supadata", supadata, "yes (206 = 1 credit)", "yes", "YouTube, TikTok, IG, X, FB, files, web"),
    ("ScrapeCreators", scrapecreators, "no", "no (never expire)", "many social platforms"),
    ("SocialKit (annual billing)", socialkit, "not stated", "yes", "many social platforms"),
    ("youtube-transcript.io", youtube_transcript_io, "not stated", "not stated", "YouTube"),
    ("SearchAPI", searchapi, "not stated", "not stated", "search engines incl. YouTube"),
    ("SerpApi", serpapi, "likely (empty results count)", "yes (reset each cycle)", "search engines incl. YouTube"),
    ("Scrapingdog", scrapingdog, "not stated", "not stated", "scraping APIs incl. YouTube"),
    ("Apify Store Actor (cheapest)", apify_cheapest, "varies by Actor", "per Actor", "per Actor"),
]


def rows_for(n, no_captions):
    missing = round(n * no_captions)
    captioned = n - missing
    out = []
    for name, fn, misses, expire, covers in PROVIDERS:
        billed = n if misses.startswith(("yes", "likely")) else captioned
        cost = fn(billed)
        out.append({"provider": name, "requests_billed": billed, "monthly_usd": None if cost is None else round(cost, 2),
                    "misses_billed": misses, "credits_expire": expire, "covers": covers})
    out.sort(key=lambda r: (r["monthly_usd"] is None, r["monthly_usd"] or 0))
    return out, captioned, missing


def main(argv=None):
    p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    p.add_argument("--per-month", type=int, required=True, help="transcript requests a month")
    p.add_argument("--no-captions", type=float, default=0.0, help="share of videos without captions (0-1)")
    p.add_argument("--json", action="store_true", help="print JSON instead of a table")
    args = p.parse_args(argv)
    if args.per_month < 1:
        p.error("--per-month must be at least 1")
    if not 0 <= args.no_captions <= 1:
        p.error("--no-captions is a share such as 0.12")
    rows, captioned, missing = rows_for(args.per_month, args.no_captions)
    if args.json:
        json.dump({"checked": CHECKED, "per_month": args.per_month, "with_captions": captioned,
                   "without_captions": missing, "rows": rows}, sys.stdout, indent=2)
        print()
        return 0
    print(f"{args.per_month:,} requests a month ({captioned:,} with captions, {missing:,} without). "
          f"List prices checked {CHECKED}.\n")
    print(f"{'Provider':42} {'$/month':>9}  {'Misses billed':28} Credits expire")
    for r in rows:
        cost = "custom" if r["monthly_usd"] is None else f"{r['monthly_usd']:,.2f}"
        print(f"{r['provider']:42} {cost:>9}  {r['misses_billed']:28} {r['credits_expire']}")
    print("\nYouTubeTranscriptAPI 'founding' prices apply if you subscribe within 7 days of signing up;")
    print("'standard' prices apply after that.")
    print("'custom' means the volume is above the largest published plan. ScrapeCreators and")
    print("Apify are pay-as-you-go: the figure is your spend spread over the months a pack lasts.")
    print("None of these fetch transcripts for videos without captions except Supadata (2 credits")
    print("a minute on its default mode) and some Apify Actors; that cost isn't included here.")
    return 0


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