<?php

namespace XZD\AI\V5\REST\Controllers;

use XZD\AI\V5\REST\BaseController;
use XZD\AI\V5\Tools\ToolRegistry;
use WP_REST_Request;

class ToolController extends BaseController
{
    public function registerRoutes(): void
    {
        $this->registerGet('/tools', [$this, 'index'], 'manage_options');
        $this->registerGet('/tools/(?P<id>[a-zA-Z0-9_]+)', [$this, 'show'], 'manage_options');
        $this->registerPost('/tools/(?P<id>[a-zA-Z0-9_]+)/test', [$this, 'test'], 'manage_options');
        $this->registerPost('/tools/(?P<id>[a-zA-Z0-9_]+)/toggle', [$this, 'toggle'], 'manage_options');
    }

    public function index(WP_REST_Request $request): \WP_REST_Response
    {
        if ($err = $this->guardLicense('free')) return $err;
        $registry = ToolRegistry::instance();
        $category = $request->get_param('category');
        $search = $request->get_param('search');

        $tools = $category ? $registry->getByCategory($category) : $registry->getAll();

        if ($search) {
            $tools = array_filter($tools, fn($t) =>
                stripos($t->id, $search) !== false ||
                stripos($t->name, $search) !== false
            );
        }

        $list = array_values(array_map(fn($t) => $t->toArray(), $tools));

        return $this->success([
            'tools'         => $list,
            'total'         => count($list),
            'stats'         => $registry->getStats(),
            'blocked_tools' => \XZD\AI\V5\Core\Config::instance()->get('tools.blocked_tools', []),
        ]);
    }

    public function show(WP_REST_Request $request): \WP_REST_Response
    {
        if ($err = $this->guardLicense('free')) return $err;
        $tool = ToolRegistry::instance()->get($request->get_param('id'));
        if (!$tool) return $this->error('工具不存在', 'not_found', 404);
        return $this->success(array_merge($tool->toArray(), ['schema' => $tool->schema]));
    }

    public function test(WP_REST_Request $request): \WP_REST_Response
    {
        if ($err = $this->guardLicense('free')) return $err;
        $id = $request->get_param('id');
        $params = $this->getBodyParams($request);
        $userId = get_current_user_id();

        $result = ToolRegistry::instance()->execute($id, $params, $userId);
        return $this->success($result->toArray(), $result->message);
    }

    public function toggle(WP_REST_Request $request): \WP_REST_Response
    {
        if ($err = $this->guardLicense('free')) return $err;
        $id = $request->get_param('id');
        $tool = ToolRegistry::instance()->get($id);
        if (!$tool) return $this->error('工具不存在', 'not_found', 404);

        $blocked = \XZD\AI\V5\Core\Config::instance()->get('tools.blocked_tools', []);
        if (in_array($id, $blocked, true)) {
            $blocked = array_diff($blocked, [$id]);
        } else {
            $blocked[] = $id;
        }
        \XZD\AI\V5\Core\Config::instance()->set('tools.blocked_tools', array_values($blocked))->save();

        return $this->success(['blocked' => in_array($id, $blocked, true)], '工具状态已切换');
    }
}
