"""Emit Markdown sections with heading paths and one-based source lines."""
import argparse
import json
from pathlib import Path
from markdown_it import MarkdownIt

parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("source", type=Path)
args = parser.parse_args()
source = args.source.read_text(encoding="utf-8")
lines = source.splitlines()
tokens = MarkdownIt("commonmark").parse(source)
headings = [(token.map[0], token.map[1], int(token.tag[1]), tokens[i + 1].content)
            for i, token in enumerate(tokens)
            if token.type == "heading_open" and token.level == 0 and token.map]
path = []
if not headings or headings[0][0] > 0:
    headings.insert(0, (0, 0, 0, ""))
for i, (start, heading_end, level, title) in enumerate(headings):
    end = headings[i + 1][0] if i + 1 < len(headings) else len(lines)
    while path and path[-1][0] >= level:
        path.pop()
    if title:
        path.append((level, title))
    while end > start and not lines[end - 1].strip():
        end -= 1
    if end > heading_end:
        print(json.dumps({"source": args.source.name, "start_line": start + 1,
                          "end_line": end, "headings": [label for _, label in path],
                          "text": "\n".join(lines[start:end])}, ensure_ascii=False))
