<?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 UpdateConversationSummaryTool extends AbstractTool implements ToolPromptAdditionInterface
{
    public function name()
    {
        return 'update_conversation_summary';
    }

    public function description()
    {
        return 'Update the rolling summary for the current conversation.';
    }

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

    public function promptAddition()
    {
        return 'When the conversation evolves, maintain a concise rolling summary that captures the current state and context.';
    }

    public function handle(array $arguments, ToolExecutionContext $context = null)
    {
        $conversation = $this->requireConversation($context);
        $conversation->memory()->summary(isset($arguments['summary']) ? $arguments['summary'] : '');
        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;
    }
}
