<?php

namespace XZD\AI\V5\Tools;

/**
 * 工具执行统一返回格式
 */
class ToolResult
{
    private function __construct(
        public bool   $success,
        public mixed  $data = null,
        public string $message = '',
        public string $errorCode = '',
        public ?array $undoData = null,
        public int    $durationMs = 0,
        public int    $tokensUsed = 0,
        public float  $costRmb = 0,
    ) {}

    public static function success(mixed $data = null, string $message = 'ok', array $extra = []): self
    {
        return new self(
            success: true,
            data: $data,
            message: $message,
            undoData: $extra['undo_data'] ?? null,
            durationMs: $extra['duration_ms'] ?? 0,
            tokensUsed: $extra['tokens_used'] ?? 0,
            costRmb: $extra['cost_rmb'] ?? 0,
        );
    }

    public static function error(string $message, string $code = 'error', mixed $data = null): self
    {
        return new self(
            success: false,
            data: $data,
            message: $message,
            errorCode: $code,
        );
    }

    public function toArray(): array
    {
        return [
            'success'     => $this->success,
            'data'        => $this->data,
            'message'     => $this->message,
            'code'        => $this->errorCode ?: ($this->success ? 'ok' : 'error'),
            'undo_data'   => $this->undoData,
            'duration_ms' => $this->durationMs,
            'tokens_used' => $this->tokensUsed,
            'cost_rmb'    => $this->costRmb,
        ];
    }
}
