"""
GLAMWalk -- Volume 4: Libraries & Archives
08_chapter_splitter.py

The heuristic chapter-splitter for raw Gutenberg text, with a safe whole-book fallback so it never produces zero chapters.

Source: Volume Four, Section 1.8
Targets Python 3.11.4 -- see Volume One, Chapter 1.5/1.6.
"""

import re

CHAPTER_PATTERN = re.compile(
    r'^\s*(CHAPTER|Chapter)\s+([IVXLCDM]+|\d+)\.?\s*$',
    re.MULTILINE,
)

def split_into_chapters(full_text):
    matches = list(CHAPTER_PATTERN.finditer(full_text))
    if not matches:
        return [{"title": "Full Text", "body": full_text}]   # never zero chapters

    chapters = []
    for i, match in enumerate(matches):
        start = match.end()
        end = matches[i + 1].start() if i + 1 < len(matches) else len(full_text)
        chapters.append({
            "title": match.group(0).strip(),
            "body": full_text[start:end].strip(),
        })
    return chapters
