<?php
namespace boru\ai\Cli;

use boru\ai\Conversation\ConversationReference;
use boru\ai\Persistence\Db\DbConfig;
use boru\ai\Persistence\Db\DbConnection;
use boru\ai\Persistence\Db\DbConversationInspector;
use boru\cli2\CLIContext;
use boru\cli2\Contracts\CommandDescriptionInterface;
use boru\cli2\Contracts\CommandInterface;
use boru\cli2\Contracts\CommandParamsInterface;
use boru\cli2\Params\Option;

class ToolCallsListCommand implements CommandInterface, CommandParamsInterface, CommandDescriptionInterface
{
    public function name()
    {
        return 'tool-calls:list';
    }

    public function description()
    {
        return 'List persisted tool call rows for a conversation or specific turn';
    }

    public function commandParams()
    {
        return array(
            Option::create('conversation-id|conversation-id|Conversation id'),
            Option::create('reference|reference|External conversation reference'),
            Option::create('user-id|user-id|Optional user id for external reference lookup'),
            Option::create('turn-number|turn-number|Optional turn number filter'),
        );
    }

    public function handle(CLIContext $ctx)
    {
        $reference = new ConversationReference();
        if ($ctx->get('conversation-id')) {
            $reference->id($ctx->get('conversation-id'));
        }
        if ($ctx->get('reference')) {
            $reference->externalReference($ctx->get('reference'));
        }
        if ($ctx->get('user-id')) {
            $reference->userId($ctx->get('user-id'));
        }

        $config = DbConfig::fromConfig($ctx->get('config'));
        $inspector = new DbConversationInspector(new DbConnection($config));
        $conversation = $inspector->loadConversationRecord($reference);

        if (!$conversation) {
            $ctx->output('Conversation not found.');
            return false;
        }

        $turns = $inspector->listTurnRecords($conversation['id']);
        $turnNumberFilter = $ctx->get('turn-number');

        foreach ($turns as $turn) {
            if ($turnNumberFilter !== null && (int)$turn['turn_number'] !== (int)$turnNumberFilter) {
                continue;
            }

            $toolCalls = $inspector->listToolCallRecords($turn['id']);
            if (empty($toolCalls)) {
                continue;
            }

            $ctx->output('Turn #' . $turn['turn_number'] . ' [' . $turn['status'] . ']');
            foreach ($toolCalls as $toolCall) {
                $ctx->output('  [' . $toolCall['sequence_number'] . '] ' . $toolCall['name'] . ' | status=' . $toolCall['status'] . ' | success=' . $toolCall['success']);
                $ctx->output('      tool_call_id: ' . $toolCall['tool_call_id']);
                $ctx->output('      arguments_json: ' . $toolCall['arguments_json']);
                $ctx->output('      result_json: ' . $toolCall['result_json']);
            }
        }

        return true;
    }
}
