<?php
namespace boru\ai\Conversation\Tool;

use boru\ai\AI;
use boru\ai\Conversation\Conversation;
use boru\ai\Runtime\AbstractTool;
use boru\ai\Runtime\ToolExecutionContext;
use boru\ai\Runtime\ToolPromptAdditionInterface;

class UpdateConversationTitleTool extends AbstractTool implements ToolPromptAdditionInterface
{
    public function name()
    {
        return 'update_conversation_title';
    }

    public function description()
    {
        return 'Update the current conversation title with a short, useful label.';
    }

    public function schema()
    {
        return array(
            'type' => 'object',
            'properties' => array(
                'title' => array(
                    'type' => 'string',
                    'description' => 'Short conversation title.',
                ),
            ),
            'required' => array('title'),
        );
    }

    public function promptAddition()
    {
        return 'When it would help with continuity, keep the conversation title updated with a short, useful label.';
    }

    public function handle(array $arguments, ToolExecutionContext $context = null)
    {
        $conversation = $this->requireConversation($context);
        $conversation->memory()->title(isset($arguments['title']) ? $arguments['title'] : '');
        AI::persistence()->saveConversation($conversation);
        return $conversation->memory()->toArray();
    }

    protected function requireConversation(ToolExecutionContext $context = null)
    {
        $request = $context ? $context->request() : null;
        $conversation = $request ? $request->metadata('conversation') : null;
        if (!$conversation instanceof Conversation) {
            throw new \RuntimeException('Conversation memory tools require an active conversation context');
        }
        return $conversation;
    }
}
