#!/usr/bin/env python3
"""Reflow soft-wrapped markdown into one physical line per logical line/list item.

Confluence's markdown->ADF converter chokes on continuation lines (soft wraps)
inside list items, especially ones starting with "+ `code`". Fix: join wrapped
continuation lines back into their parent line with a single space, leaving
fenced code blocks, table rows, and blank-line paragraph breaks untouched.
"""
import re
import sys

# Zero leading whitespace only -- neither doc has nested lists, so any
# indented line is a continuation of the current item, never a new one
# (this ambiguity -- e.g. a "  + `code`" continuation line that merely
# happens to start with a literal "+" -- is exactly what broke Confluence's
# markdown parser).
LIST_MARKER = re.compile(r'^([-*+]|\d+\.)\s')
HEADING = re.compile(r'^#{1,6}\s')
TABLE_ROW = re.compile(r'^\s*\|')
FENCE = re.compile(r'^\s*```')
HR = re.compile(r'^\s*(---+|\*\*\*+|___+)\s*$')
BLOCKQUOTE = re.compile(r'^\s*>')

def reflow(text: str) -> str:
    lines = text.split('\n')
    out = []
    in_fence = False
    current = None  # index in out of the line currently being built

    for raw in lines:
        if FENCE.match(raw):
            in_fence = not in_fence
            out.append(raw)
            current = None
            continue

        if in_fence:
            out.append(raw)
            continue

        if raw.strip() == '':
            out.append(raw)
            current = None
            continue

        if TABLE_ROW.match(raw) or HEADING.match(raw) or HR.match(raw) or BLOCKQUOTE.match(raw):
            out.append(raw)
            current = None
            continue

        if LIST_MARKER.match(raw):
            out.append(raw)
            current = len(out) - 1
            continue

        # Continuation line: starts with whitespace (indented under a list item)
        # or is a plain paragraph continuation (no marker, previous line was
        # also a continuation/anchor, not blank).
        if current is not None:
            out[current] = out[current].rstrip() + ' ' + raw.strip()
        else:
            # Plain paragraph continuation with no preceding list item this block
            if out and out[-1].strip() != '' and not (
                TABLE_ROW.match(out[-1]) or HEADING.match(out[-1]) or HR.match(out[-1])
            ):
                out[-1] = out[-1].rstrip() + ' ' + raw.strip()
                current = len(out) - 1
            else:
                out.append(raw)
                current = len(out) - 1

    return '\n'.join(out)


if __name__ == '__main__':
    path = sys.argv[1]
    with open(path, 'r') as f:
        content = f.read()
    result = reflow(content)
    outpath = sys.argv[2] if len(sys.argv) > 2 else path + '.reflowed'
    with open(outpath, 'w') as f:
        f.write(result)
    print(f"wrote {outpath}")
