#!/usr/bin/env python3
from pathlib import Path
import re, json
BASE=Path('/home/spazio/cosmos_books/talk-to-the-entities-beginning-manual')
full=(BASE/'text/book_full.txt').read_text(encoding='utf-8')
parts=re.split(r'\n\n--- PAGE (\d+) ---\n\n', full)
pages=[]
for i in range(1,len(parts),2):
    n=int(parts[i]); text=parts[i+1]
    if n < 4: continue
    # Remove recurring headers/footers while keeping the substantive source wording.
    lines=[]
    for line in text.splitlines():
        s=line.strip()
        if re.match(r'^АВГУСТА 2019 РАЗГОВОР С СУЩНОСТЯМИ',s): continue
        if s.startswith('© 2019 Шэннон О') or s.startswith('Этот материал не может быть') or s.startswith('переведен без письменного'): continue
        lines.append(line)
    text='\n'.join(lines).strip()
    pages.append((n,text))
frags=[]; cur=[]; chars=0
TARGET=12500
for n,text in pages:
    block=f'--- PAGE {n:02d} ---\n{text}\n'
    if cur and chars+len(block)>TARGET:
        frags.append(cur); cur=[]; chars=0
    cur.append((n,block)); chars+=len(block)
if cur: frags.append(cur)
outdir=BASE/'daily_fragments'; outdir.mkdir(parents=True,exist_ok=True)
manifest=[]
for idx,frag in enumerate(frags,1):
    p=outdir/f'fragment_{idx:03d}.txt'
    body='\n\n'.join(x[1] for x in frag)
    p.write_text(body,encoding='utf-8')
    manifest.append({'fragment_number':idx,'file':p.name,'start_page':frag[0][0],'end_page':frag[-1][0],'characters':len(body)})
meta={'book':'Шэннон О’Хара — Разговор с сущностями: Начало (август 2019, русская версия)','source_pdf':str(BASE/'source/TTTE_Beginning_Manual_AUG_2019_RUSSIAN.pdf'),'ocr_text':str(BASE/'text/book_full.txt'),'total_pages':85,'content_start_page':4,'total_fragments':len(manifest),'fragments':manifest}
(BASE/'manifest.json').write_text(json.dumps(meta,ensure_ascii=False,indent=2),encoding='utf-8')
(BASE/'state.json').write_text(json.dumps({'next_fragment':1},ensure_ascii=False,indent=2),encoding='utf-8')
(BASE/'TOOLS_AND_INSIGHTS.md').write_text('# Разговор с сущностями — инструменты и смыслы\n\nНакопительная выжимка по книге с отдельным переводом идей в язык Cosmos Luminosity.\n',encoding='utf-8')
print(json.dumps({'total_fragments':len(manifest),'first':manifest[0],'last':manifest[-1]},ensure_ascii=False,indent=2))
