#!/usr/bin/env python3
"""unwrap-copy.py — join hard-wrapped prose lines, preserve structure.

Pure filter: stdin → unwrapped text → stdout. Callers pipe to pbcopy
(`mux copy`, and the copy-mode Y binding in mux.tmux.conf).

Heuristic: a line is "wrap-broken" when it runs close to the longest
line in the input — terminal-width wrapping leaves no short lines
mid-paragraph. Blank lines (paragraph breaks), fenced code blocks,
indented blocks, and list-item starts pass through untouched, so code
survives while prose unwraps. List items join their own wrapped
continuation lines.
"""

import re
import sys


LIST_RE = re.compile(r"^\s*([-*+•]|\d+[.)]|>)\s")


def breaks_join(line):
    """A line that must start fresh, never be appended to the previous."""
    s = line.strip()
    return (
        not s
        or s.startswith("```")
        or line.startswith(("    ", "\t"))
        or bool(LIST_RE.match(line))
    )


def unwrap(text):
    lines = [l.rstrip() for l in text.split("\n")]

    # Lines near the longest one were likely wrapped at that width.
    maxlen = max((len(l) for l in lines), default=0)
    threshold = max(40, maxlen - 15)

    out = []
    in_fence = False
    i = 0
    while i < len(lines):
        line = lines[i]
        if line.strip().startswith("```"):
            in_fence = not in_fence
            out.append(line)
            i += 1
            continue
        # Pass through verbatim — except list items, which fall through so
        # their wrapped continuation lines can join them.
        if in_fence or (breaks_join(line) and not LIST_RE.match(line)):
            out.append(line)
            i += 1
            continue

        buf = line
        j = i + 1
        while j < len(lines) and len(lines[j - 1]) >= threshold:
            nxt = lines[j]
            if breaks_join(nxt):
                break
            buf += " " + nxt.strip()
            j += 1
        out.append(buf)
        i = j

    return "\n".join(out)


if __name__ == "__main__":
    sys.stdout.write(unwrap(sys.stdin.read()))
