<?php

Kirby::plugin('novelcrafter/ai', [
    'options' => [
        'openRouterApiKey' => null,
        'defaultModel'     => 'anthropic/claude-3-haiku:beta',
        'maxTokens'        => 2000,
        'systemPrompt'     => 'You are a literary author. Output only the requested prose — no preamble, no commentary, no titles, no meta-sentences like "here is your story". Begin writing immediately and stop when the content is complete.',
    ],
]);

class NovelCrafterAI
{
    private string $apiKey;
    private string $model;

    public function __construct()
    {
        $this->apiKey = option('novelcrafter.ai.openRouterApiKey') ?? '';
        $this->model  = option('novelcrafter.ai.defaultModel', 'anthropic/claude-3-haiku:beta');

        if (empty($this->apiKey)) {
            throw new Exception('OpenRouter API key not configured. Add OPENROUTER_API_KEY to your .env file.');
        }
    }

    public function buildContext(array $pageIds): string
    {
        $context = '';

        foreach ($pageIds as $pageId) {
            $page = kirby()->page($pageId);
            if (!$page) continue;

            $textContent = $page->text_content()->value();
            if (empty($textContent)) continue;

            $context .= '## ' . $page->title()->value() . "\n\n";
            $context .= $textContent . "\n\n";
        }

        return trim($context);
    }

    public function generateText(string $context, string $prompt): string
    {
        $systemPrompt = option('novelcrafter.ai.systemPrompt', '');

        $systemContent = $systemPrompt;
        if (!empty($context)) {
            $systemContent .= "\n\nUse the following story context to inform your writing:\n\n" . $context;
        }

        $messages = [
            [
                'role'    => 'system',
                'content' => $systemContent,
            ],
            [
                'role'    => 'user',
                'content' => $prompt,
            ],
        ];

        $payload = [
            'model'       => $this->model,
            'messages'    => $messages,
            'max_tokens'  => option('novelcrafter.ai.maxTokens', 2000),
            'temperature' => 0.7,
        ];

        $ch = curl_init('https://openrouter.ai/api/v1/chat/completions');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Authorization: Bearer ' . $this->apiKey,
            'Content-Type: application/json',
        ]);

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($httpCode !== 200) {
            $error = json_decode($response, true);
            $msg   = $error['error']['message'] ?? $response;
            throw new Exception('OpenRouter error (' . $httpCode . '): ' . $msg);
        }

        $result = json_decode($response, true);

        if (!isset($result['choices'][0]['message']['content'])) {
            throw new Exception('Unexpected API response format.');
        }

        return trim($result['choices'][0]['message']['content']);
    }
}
