<?php

namespace App\Controllers;

/**
 * Shared draft-only text generation for the F&B menu editor and the
 * Events form — one endpoint rather than two near-identical copies,
 * since both are the same interaction shape (a short prompt/bullets in,
 * a polished description out, in the hotel's tone). No tools (nothing
 * here needs a live data lookup) and no auto-publish: the drafted text
 * is returned to the browser and lands in the existing description
 * textarea for staff to edit and save themselves, exactly like every
 * other field on those forms.
 */
class AiWriterController extends BaseController
{
    private const CONTEXTS = [
        'menu_item' => 'a food/drink menu item',
        'event'     => 'an event package offered by the hotel (e.g. a wedding, conference, or private dining package)',
    ];

    public function draftDescription()
    {
        if (service('settings')->get('ai.menu_event_writer_enabled', '1') !== '1') {
            return $this->response->setJSON(['success' => false, 'error' => 'The description writer is turned off — enable it under Settings > AI Features.', 'csrf_hash' => csrf_hash()]);
        }

        $context = $this->request->getPost('context');
        $name    = trim((string) $this->request->getPost('name'));
        $prompt  = trim((string) $this->request->getPost('prompt'));

        if (! isset(self::CONTEXTS[$context])) {
            return $this->response->setJSON(['success' => false, 'error' => 'Invalid context.', 'csrf_hash' => csrf_hash()]);
        }

        if ($name === '' && $prompt === '') {
            return $this->response->setJSON(['success' => false, 'error' => 'Give it a name and/or a few bullet points first.', 'csrf_hash' => csrf_hash()]);
        }

        $voice = service('settings')->get('ai.brand_voice') ?: 'professional, warm, and welcoming — typical of an independent hotel';

        $systemPrompt = 'You write short, polished marketing copy for a hotel. You will be given the name and a few '
            . "bullet points or a short prompt describing {$this->contextLabel($context)}. Write ONE description, "
            . "2-4 sentences, in this tone: {$voice}. Do not invent facts, prices, ingredients, or details beyond "
            . 'what the staff member gave you — only phrase what they told you more polished. Return only the '
            . 'description text itself, no heading, no quotes, no markdown.';

        $userMessage = trim("Name: {$name}\n\nDetails: {$prompt}");

        $result = service('claudeService')->chat(
            'menu_event_writer',
            $systemPrompt,
            [['role' => 'user', 'content' => $userMessage]],
            [],
            null,
            $context,
            null,
            $this->currentUserId(),
        );

        if (! $result['success']) {
            return $this->response->setJSON(['success' => false, 'error' => $result['error'], 'csrf_hash' => csrf_hash()]);
        }

        return $this->response->setJSON(['success' => true, 'text' => trim((string) $result['text'], " \t\n\r\0\x0B\""), 'csrf_hash' => csrf_hash()]);
    }

    private function contextLabel(string $context): string
    {
        return self::CONTEXTS[$context] ?? 'an item';
    }
}
