#!/usr/bin/env python3
"""outline.py post.md  ->  a first-draft carousel outline from a blog post written in Markdown.
One slide per "## " heading: the heading is the slide headline, the first sentence under it is the body.
The "# " title becomes the cover. Bodies over the word limit are flagged for you to shorten by hand. Standard library only."""
import re, sys
LIMIT = 25  # words; the body size that fit at 46 px in our transcript-to-carousel test
def first_sentence(text):
    text = " ".join(text.split())
    m = re.match(r"(.+?[.!?])(\s|$)", text)
    return m.group(1) if m else text
def main(path):
    lines = open(path, encoding="utf-8").read().splitlines()
    title = next((l[2:].strip() for l in lines if l.startswith("# ")), "")
    sections, cur = [], None
    for l in lines:
        if l.startswith("## "):
            cur = [l[3:].strip(), []]; sections.append(cur)
        elif cur is not None and l.strip() and not l.startswith("#"):
            cur[1].append(l.strip())
    if not sections:
        print("no '## ' headings found: this script needs a post with section headings. Add them, or outline the post by hand."); return 2
    words_in = len(re.findall(r"\S+", " ".join(l for l in lines if not l.startswith("#"))))
    print(f"post: {words_in} words under {len(sections)} headings")
    print(f"slide 1 (cover) | {title}")
    total = len(title.split()); over = 0
    for i, (head, body) in enumerate(sections, 2):
        s = first_sentence(" ".join(body)); n = len(s.split()); total += len(head.split()) + n
        flag = "" if n <= LIMIT else f"  <-- {n} words, shorten to {LIMIT} or fewer"; over += n > LIMIT
        print(f"slide {i} | {head} | {s}{flag}")
    print(f"slides: {len(sections) + 1}; words on slides: {total} = {total / words_in * 100:.1f}% of the post; bodies over {LIMIT} words: {over}")
    return 0
if __name__ == "__main__":
    sys.exit(main(sys.argv[1]))
