<?php

use Bnomei\Janitor;
use Kirby\CLI\CLI;

return [
    'description' => 'Generate AI text for a chapter using OpenRouter',
    'args' => [] + Janitor::ARGS, // page, file, user, site, data, model
    'command' => static function (CLI $cli): void {
        $page = $cli->kirby()->page($cli->arg('page'));

        if (!$page || $page->template()->name() !== 'chapter') {
            janitor()->data($cli->arg('command'), [
                'status' => 400,
                'message' => 'Invalid page — must be a chapter',
            ]);
            return;
        }

        $prompt = $page->prompt()->value();

        if (empty(trim($prompt))) {
            janitor()->data($cli->arg('command'), [
                'status' => 400,
                'message' => 'Please enter a prompt before generating',
            ]);
            return;
        }

        // Build list of context page IDs
        $contextPageIds = [];

        if ($page->use_whole_novel()->isTrue()) {
            // All chapter pages
            foreach ($cli->kirby()->site()->children()->filterBy('intendedTemplate', 'chapter') as $chapter) {
                $contextPageIds[] = $chapter->id();
            }
        } else {
            // Selected chapters
            foreach ($page->selected_chapters()->toPages() as $chapter) {
                $contextPageIds[] = $chapter->id();
            }
        }

        // Selected codex entries
        foreach ($page->selected_codex()->toPages() as $codexPage) {
            $contextPageIds[] = $codexPage->id();
        }

        try {
            $ai = new NovelCrafterAI();
            $context = $ai->buildContext($contextPageIds);
            $response = $ai->generateText($context, $prompt);

            // Append to chat history
            $chatHistory = $page->chat_history()->toStructure()->toArray();
            $chatHistory[] = [
                'prompt'    => $prompt,
                'response'  => $response,
                'timestamp' => date('Y-m-d H:i:s'),
            ];

            $page->update([
                'chat_history' => $chatHistory,
            ]);

            janitor()->data($cli->arg('command'), [
                'status'  => 200,
                'message' => 'Response saved to chat history',
                'reload'  => true,
            ]);
        } catch (Exception $e) {
            janitor()->data($cli->arg('command'), [
                'status'  => 500,
                'message' => $e->getMessage(),
            ]);
        }
    },
];
