import { useRef, useState } from 'preact/hooks';
import { useAppState, type AppState } from '../contexts/state';
import Chapters from './chapters';
import LLM from './llm';

export function useChapterSummarization() {
    const state = useAppState();
    const stateRef = useRef<AppState>(state);
    stateRef.current = state;

    const [isSummarizing, setIsSummarizing] = useState(false);

    const summarizeAll = async () => {
        const { currentWorld, currentStory, connection, model, dispatch } = stateRef.current;
        if (!currentWorld || !currentStory || !connection || !model || isSummarizing) return;

        setIsSummarizing(true);
        try {
            const parsed = Chapters.parseText(currentStory.text);
            const validHashes: Record<string, Chapters.Hash[]> = {};

            for (const parsedChapter of parsed) {
                const chunks = Chapters.splitIntoChunks(parsedChapter.body);
                const cachedChapter = (currentStory.chapters ?? [])
                    .find(c => c.header === parsedChapter.header)
                    ?? Chapters.emptyChapter(parsedChapter.header);

                validHashes[parsedChapter.header] = [];

                for (const body of chunks) {
                    const { hash, summary } = Chapters.lookupSummary(cachedChapter, body);

                    if (summary === null) {
                        const newSummary = await LLM.summarize(connection, model.id, body);
                        dispatch({
                            type: 'STORE_CHAPTER_SUMMARY',
                            worldId: currentWorld.id,
                            storyId: currentStory.id,
                            header: parsedChapter.header,
                            hash,
                            summary: newSummary,
                        });
                    }

                    validHashes[parsedChapter.header].push(hash);
                }
            }

            // Clean up stale cache entries
            dispatch({
                type: 'CLEAN_CHAPTER_SUMMARIES',
                worldId: currentWorld.id,
                storyId: currentStory.id,
                validHashes,
            });
        } finally {
            setIsSummarizing(false);
        }
    };

    return { summarizeAll, isSummarizing };
}
