#!/usr/bin/env python3
import argparse, json, pathlib, sys
from datetime import datetime, timezone

BASE = pathlib.Path('/home/spazio/aroma_hunter_daily')
TEXT = BASE / 'text'
MANIFEST = TEXT / 'manifest.json'
STATE = BASE / 'state.json'
OUTPUTS = BASE / 'daily_outputs'

SKIP_CHARS_UNDER = 1000


def load_json(path, default=None):
    if path.exists():
        return json.loads(path.read_text(encoding='utf-8'))
    return default


def save_json(path, data):
    path.write_text(json.dumps(data, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('--peek', action='store_true', help='Do not advance state')
    args = ap.parse_args()

    if not MANIFEST.exists():
        print(json.dumps({
            'status': 'missing_source',
            'message': 'FB2 text/manifest not found. Upload/extract the book first.',
            'project_dir': str(BASE)
        }, ensure_ascii=False))
        return

    manifest = load_json(MANIFEST)
    chapters = manifest.get('chapters', [])
    state = load_json(STATE, {'next_chapter': 3, 'started_at_chapter': 3, 'completed_chapters': []})
    next_idx = int(state.get('next_chapter', 3))

    chosen = None
    for ch in chapters:
        if int(ch['index']) >= next_idx and int(ch.get('chars', 0)) >= SKIP_CHARS_UNDER:
            chosen = ch
            break

    if not chosen:
        print(json.dumps({
            'status': 'complete',
            'book': manifest.get('book_title'),
            'authors': manifest.get('authors', []),
            'message': 'All substantive chapters have been processed.',
            'state': state
        }, ensure_ascii=False))
        return

    chapter_path = TEXT / chosen['file']
    fragment_text = chapter_path.read_text(encoding='utf-8')
    substantive = [c for c in chapters if int(c.get('chars', 0)) >= SKIP_CHARS_UNDER]
    substantive_indices = [int(c['index']) for c in substantive]
    fragment_number = substantive_indices.index(int(chosen['index'])) + 1 if int(chosen['index']) in substantive_indices else int(chosen['index'])

    result = {
        'status': 'ok',
        'book': manifest.get('book_title'),
        'authors': manifest.get('authors', []),
        'chapter_index': int(chosen['index']),
        'chapter_title': chosen.get('title'),
        'chapter_file': str(chapter_path),
        'fragment_number': fragment_number,
        'total_fragments': len(substantive),
        'chars': len(fragment_text),
        'project_dir': str(BASE),
        'accumulating_markdown': str(BASE / 'TOOLS_AND_INSIGHTS.md'),
        'daily_outputs_dir': str(OUTPUTS),
        'fragment_text': fragment_text
    }

    if not args.peek:
        completed = state.setdefault('completed_chapters', [])
        if int(chosen['index']) not in completed:
            completed.append(int(chosen['index']))
        state['next_chapter'] = int(chosen['index']) + 1
        state['last_emitted_at'] = datetime.now(timezone.utc).isoformat()
        state['last_chapter'] = int(chosen['index'])
        save_json(STATE, state)

    print(json.dumps(result, ensure_ascii=False))

if __name__ == '__main__':
    main()
