#!/usr/bin/env python3
import os
import re

chapters_dir = "../chapters"
audiobook_dir = "."
output_file = "manifest.md"

lines = []
lines.append("# The Testament - Audiobook Samples")
lines.append("")
lines.append("| Chapter | Title | Audio Sample |")
lines.append("|---------|-------|--------------|")

for i in range(1, 19):
    chapter_num = f"{i:02d}"
    chapter_file = os.path.join(chapters_dir, f"chapter-{chapter_num}.md")
    if not os.path.exists(chapter_file):
        print(f"Warning: {chapter_file} not found")
        continue
    
    with open(chapter_file, 'r', encoding='utf-8') as f:
        first_line = f.readline().strip()
    
    # Extract title after "# Chapter X — " or "# Chapter X - "
    match = re.match(r'#\s*Chapter\s+\d+\s*[—–-]\s*(.*)', first_line)
    if match:
        title = match.group(1).strip()
    else:
        title = first_line.lstrip('#').strip()
    
    ogg_file = f"ch{chapter_num}-sample.ogg"
    ogg_path = os.path.join(audiobook_dir, ogg_file)
    if os.path.exists(ogg_path):
        lines.append(f"| {i} | {title} | [{ogg_file}]({ogg_file}) |")
    else:
        lines.append(f"| {i} | {title} | MISSING |")

with open(output_file, 'w', encoding='utf-8') as f:
    f.write('\n'.join(lines))

print(f"Manifest written to {output_file}")