#!/usr/bin/env python3
import json
from pathlib import Path

BOOK_DIR = Path('/home/spazio/.hermes/books/bog-vsegda-puteshestvuet-inkognito')
MANIFEST = BOOK_DIR / 'manifest.json'
STATE = BOOK_DIR / 'daily_state.json'

manifest = json.loads(MANIFEST.read_text(encoding='utf-8'))
if STATE.exists():
    state = json.loads(STATE.read_text(encoding='utf-8'))
else:
    state = {'next_real_chapter': 1}

next_ch = int(state.get('next_real_chapter', 1))
chapters = {int(ch['title']): ch for ch in manifest['chapters'] if str(ch.get('title','')).isdigit()}
max_ch = max(chapters) if chapters else 0

if next_ch > max_ch:
    print(json.dumps({
        'done': True,
        'book_title': manifest.get('book_title'),
        'author': ', '.join(manifest.get('authors', [])),
        'message': 'Все главы уже отправлены.',
        'total_chapters': max_ch
    }, ensure_ascii=False))
    raise SystemExit(0)

ch = chapters[next_ch]
text = (BOOK_DIR / ch['file']).read_text(encoding='utf-8')

# advance state so the next cron run moves to the following chapter
state['next_real_chapter'] = next_ch + 1
STATE.write_text(json.dumps(state, ensure_ascii=False, indent=2), encoding='utf-8')

print(json.dumps({
    'done': False,
    'book_title': manifest.get('book_title'),
    'author': ', '.join(manifest.get('authors', [])),
    'chapter_number': next_ch,
    'total_chapters': max_ch,
    'chapter_title': ch.get('title') or str(next_ch),
    'text': text
}, ensure_ascii=False))
