import sys, math
from srtlib import parse, cps, chars, write
src, dst, limit = sys.argv[1], sys.argv[2], float(sys.argv[3])
GAP, MAXD, MIND = 83, 7000, 833
BORROW = int(sys.argv[4]) if len(sys.argv) > 4 else 400   # 2 frames at 24 fps, Netflix max 7 s, min 5/6 s; BORROW = our cap in ms on a later start of the next cue (0 = extend only)
cues = parse(open(src, encoding="utf-8-sig").read())
ext = bor = left = 0; moved = []
for i, c in enumerate(cues):
    if cps(c) <= limit: continue
    need = math.ceil(chars(c) * 1000 / limit)          # shortest duration that reaches the limit
    nxt = cues[i+1] if i+1 < len(cues) else None
    keep = min(GAP, max(0, nxt["s"] - c["e"])) if nxt else 0   # keep the gap the cue already has, at most 83 ms; never shorten a cue
    room = (nxt["s"] - keep if nxt else c["s"] + MAXD)
    c["e"] = max(c["e"], min(c["s"] + need, room, c["s"] + MAXD))   # never earlier than the original end
    if cps(c) <= limit: ext += 1; continue
    if nxt:                                            # borrow: start the next cue a little later
        nn = cues[i+2] if i+2 < len(cues) else None
        slack = nxt["e"] - max(MIND, math.ceil(chars(nxt) * 1000 / limit)) - nxt["s"]
        d = max(0, min(BORROW, slack, c["s"] + MAXD - (nxt["s"] - keep), c["s"] + need - c["e"]))
        if d > 0:
            nxt["s"] += d; c["e"] = max(c["e"], min(c["s"] + need, nxt["s"] - keep, c["s"] + MAXD)); moved.append(d)
    if cps(c) <= limit: bor += 1
    else: left += 1
open(dst, "w", encoding="utf-8", newline="\n").write(write(cues))
print("limit=%g fixed_by_extending=%d fixed_by_borrowing=%d still_over=%d max_later_start_ms=%d" % (limit, ext, bor, left, max(moved or [0])))
