<?php

namespace XZD\AI\V5\Tools;

/**
 * 工具数据类 — 不可变值对象
 */
class Tool
{
    public function __construct(
        public string $id,
        public string $name,
        public string $description,
        public string $category,          // content|wp|seo|media|theme|knowledge|automation
        public string $danger,             // none|low|medium|high
        public string $wpCap = 'read',
        public string $minRole = 'guest',  // guest|user|vip|admin
        public bool   $themeRequired = false,
        public ?string $capabilityKey = null,
        public string $confirmMode = 'auto', // auto|single|double
        public int    $undoWindow = 0,
        public array  $schema = [],
        public mixed  $callback = null,
        public bool   $pipelineStage = false,
        public string $pipelineEvent = 'publish_post',
        public bool   $pipelineAsync = false,
        public bool   $trackProcessing = false,   // 是否写入处理标记防止重复
        public bool   $supportsOverwrite = false, // 是否支持覆盖模式重处理
    ) {}

    /** 是否为危险操作（需要确认） */
    public function isDangerous(): bool
    {
        return in_array($this->danger, ['medium', 'high'], true);
    }

    /** 是否需要确认 */
    public function needsConfirm(): bool
    {
        return $this->confirmMode !== 'auto';
    }

    /** 转换为数组 */
    public function toArray(): array
    {
        return [
            'id'             => $this->id,
            'name'           => $this->name,
            'description'    => $this->description,
            'category'       => $this->category,
            'danger'         => $this->danger,
            'wp_cap'         => $this->wpCap,
            'min_role'       => $this->minRole,
            'theme_required' => $this->themeRequired,
            'capability_key' => $this->capabilityKey,
            'confirm_mode'   => $this->confirmMode,
            'undo_window'    => $this->undoWindow,
            'pipeline_stage'     => $this->pipelineStage,
            'pipeline_event'     => $this->pipelineEvent,
            'pipeline_async'     => $this->pipelineAsync,
            'track_processing'   => $this->trackProcessing,
            'supports_overwrite' => $this->supportsOverwrite,
            'schema'             => $this->schema,
        ];
    }

    /** OpenAI function calling 格式 */
    public function toOpenAIFunction(): array
    {
        $func = [
            'name'        => $this->id,
            'description' => $this->description,
        ];

        if (!empty($this->schema['properties'] ?? [])) {
            $func['parameters'] = $this->schema;
        }

        return ['type' => 'function', 'function' => $func];
    }
}
