"""
GLAMWalk -- Volume 4: Libraries & Archives
05_gutenberg_boilerplate_stripper.py

Stripping Project Gutenberg's own legal header/footer, including the pre-1997 format, with a safe never-guess fallback.

Source: Volume Four, Section 1.5 -- Stripping Gutenberg's Own Boilerplate
Targets Python 3.11.4 -- see Volume One, Chapter 1.5/1.6.
"""

import re

PG_START = re.compile(
    r"\*\*\*\s*START OF (?:THE|THIS) PROJECT GUTENBERG EBOOK[^\n]*\*\*\*",
    re.IGNORECASE,
)
PG_END = re.compile(
    r"\*\*\*\s*END OF (?:THE|THIS) PROJECT GUTENBERG EBOOK[^\n]*\*\*\*",
    re.IGNORECASE,
)

def strip_pg_boilerplate(text):
    start = PG_START.search(text)
    end = PG_END.search(text)
    if start and end and end.start() > start.end():
        return text[start.end():end.start()].strip()
    if start:
        return text[start.end():].strip()
    # No recognizable markers found — return the text as-is rather than
    # risk truncating a real book that just uses an unrecognized format.
    return text.strip()
