#!/usr/bin/env python3
"""Unwrap manual word-wrap newlines in CHANGELOG.md.

Each logical unit (a blockquote, a bullet, or a plain paragraph) collapses to ONE physical
line so GitHub's word-wrap handles display. Structural newlines (blank lines, headers, and
bullet boundaries) are preserved.
"""
import sys

path = sys.argv[1]
with open(path, encoding="utf-8") as f:
    lines = f.read().split("\n")

out = []
buf = None          # current joinable text (already-normalized)
kind = None         # 'quote' | 'bullet' | 'para'


def flush():
    global buf, kind
    if buf is not None:
        out.append(buf)
    buf = None
    kind = None


for raw in lines:
    line = raw.rstrip("\n")
    stripped = line.strip()

    if stripped == "":
        flush()
        out.append("")
        continue

    if line.lstrip().startswith("#") and line.lstrip()[:1] == "#":
        # header — standalone
        flush()
        out.append(line)
        continue

    if line.startswith(">"):
        content = line[1:].lstrip()
        if kind == "quote":
            buf = (buf + " " + content).rstrip()
        else:
            flush()
            buf = "> " + content
            kind = "quote"
        continue

    if line.startswith("- "):
        # new bullet
        flush()
        buf = line.rstrip()
        kind = "bullet"
        continue

    if line[:1] == " ":
        # indented continuation of a bullet or paragraph
        if kind in ("bullet", "para"):
            buf = (buf + " " + stripped).rstrip()
            continue
        # stray indented line with no owner — emit as-is
        flush()
        out.append(line)
        continue

    # col-0 non-empty text, not #/>/- : a plain paragraph line
    if kind == "para":
        buf = (buf + " " + stripped).rstrip()
    else:
        flush()
        buf = stripped
        kind = "para"

flush()

# Collapse any accidental trailing multiple blanks to a single trailing newline.
text = "\n".join(out)
if not text.endswith("\n"):
    text += "\n"

with open(path, "w", encoding="utf-8", newline="\n") as f:
    f.write(text)

print("unwrapped:", path)
