import re
import os

with open('design-decisions.org', 'r') as f:
    content = f.read()

lines = content.split('\n')

in_code = False
sections = {}
current_heading = None
current_lines = []

for i, line in enumerate(lines):
    if line.startswith('#+BEGIN_SRC') or line.startswith('#+BEGIN_EXAMPLE'):
        in_code = True
    elif line.startswith('#+END_SRC') or line.startswith('#+END_EXAMPLE'):
        in_code = False

    if not in_code and re.match(r'^\* [^*]', line):
        if current_heading is not None:
            sections[current_heading] = '\n'.join(current_lines)
        current_heading = line.replace('* ', '', 1).strip()
        current_lines = [line]
    elif current_heading is not None:
        current_lines.append(line)

if current_heading is not None:
    sections[current_heading] = '\n'.join(current_lines)

print(f"Found {len(sections)} sections:")
for h in sections:
    slines = sections[h].split('\n')
    print(f"  {h} ({len(slines)} lines)")

for hname, body in sections.items():
    slug = hname.lower().replace(' & ', '-').replace(' \u2014 ', '-').replace(' ', '-')
    slug = slug.replace("'", '').replace('#', 'sharp').replace('(', '').replace(')', '')
    slug = slug.strip('-')

    body = body.strip()

    out = f"""---
title: {hname}
type: reference
tags: :passepartout:architecture:
---

{body}
"""
    path = f'design/{slug}.org'
    with open(path, 'w') as f:
        f.write(out.strip() + '\n')
    print(f"  Wrote {path}")

print("Done")
