#!/usr/bin/env python3
"""chapters.py segments.csv  ->  a YouTube chapter list for a webinar replay, checked against YouTube's published rules.
segments.csv has one line per segment: start,title   (start as H:MM:SS or MM:SS). Standard library only.
Rules checked (YouTube Help, "Video chapters", read 2026-11-21): the first timestamp is 00:00, there are at least three timestamps
in ascending order, and every chapter is at least 10 seconds long. Pass the video length as a second argument to check the last chapter."""
import sys
def secs(t):
    p = [int(x) for x in t.strip().split(":")]
    while len(p) < 3: p.insert(0, 0)
    return p[0] * 3600 + p[1] * 60 + p[2]
def stamp(s, hours):
    h, m, x = s // 3600, s % 3600 // 60, s % 60
    return f"{h}:{m:02d}:{x:02d}" if hours else f"{m:02d}:{x:02d}"
def main(path, total=None):
    rows = [l.strip().split(",", 1) for l in open(path, encoding="utf-8") if l.strip()]
    seg = [(secs(a), b.strip()) for a, b in rows]
    problems = []
    if seg[0][0] != 0: problems.append(f"the first timestamp is {rows[0][0]}, it must be 00:00")
    if len(seg) < 3: problems.append(f"{len(seg)} timestamps, at least three are needed")
    for (a, ta), (b, tb) in zip(seg, seg[1:]):
        if b <= a: problems.append(f'"{tb}" does not come after "{ta}"')
        elif b - a < 10: problems.append(f'"{ta}" is {b - a} s long, the minimum is 10 s')
    if total is not None and secs(total) - seg[-1][0] < 10: problems.append(f'the last chapter "{seg[-1][1]}" is under 10 s')
    hours = (secs(total) if total else seg[-1][0]) >= 3600
    for s, t in seg: print(f"{stamp(s, hours)} {t}")
    print("--")
    if problems:
        for p in problems: print("PROBLEM:", p)
        return 1
    print(f"OK: {len(seg)} chapters, first at 00:00, ascending, each at least 10 s")
    return 0
if __name__ == "__main__":
    sys.exit(main(*sys.argv[1:3]))
