<?php

namespace XZD\AI\V5\Tools;

/**
 * 模板/配方系统 — 保存和复用 AI 操作序列。
 * 允许将多个工具调用组合成一个"配方"，一键批量执行。
 */
class RecipeManager
{
    private static string $table = 'xzd_ai_recipes';

    /**
     * 创建配方
     */
    public static function create(array $params, int $userId): ToolResult
    {
        global $wpdb;
        $table = $wpdb->prefix . self::$table;

        $name = trim($params['name'] ?? '');
        if (empty($name)) return ToolResult::error('配方名称不能为空');

        $steps = $params['steps'] ?? [];
        if (empty($steps) || !is_array($steps)) return ToolResult::error('配方步骤不能为空');

        $inserted = $wpdb->insert($table, [
            'name'        => $name,
            'description' => $params['description'] ?? '',
            'category'    => $params['category'] ?? 'general',
            'steps'       => json_encode($steps, JSON_UNESCAPED_UNICODE),
            'author_id'  => $userId,
            'is_public'   => !empty($params['is_public']) ? 1 : 0,
            'usage_count' => 0,
            'created_at'  => current_time('mysql'),
            'updated_at'  => current_time('mysql'),
        ]);

        if (!$inserted) return ToolResult::error('配方创建失败');

        $recipeId = $wpdb->insert_id;
        return ToolResult::success(['recipe_id' => $recipeId, 'name' => $name]);
    }

    /**
     * 获取配方列表
     */
    public static function list(array $params, int $userId): ToolResult
    {
        global $wpdb;
        $table = $wpdb->prefix . self::$table;

        $category = $params['category'] ?? '';
        $search = $params['search'] ?? '';
        $limit = min((int) ($params['limit'] ?? 20), 100);

        $where = ['1=1'];
        $queryParams = [];

        // 权限：自己的 + 公开的
        $where[] = '(author_id = %d OR is_public = 1)';
        $queryParams[] = $userId;

        if ($category) {
            $where[] = 'category = %s';
            $queryParams[] = $category;
        }

        if ($search) {
            $like = '%' . $wpdb->esc_like($search) . '%';
            $where[] = '(name LIKE %s OR description LIKE %s)';
            $queryParams[] = $like;
            $queryParams[] = $like;
        }

        $queryParams[] = $limit;
        $whereClause = implode(' AND ', $where);

        $rows = $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM {$table} WHERE {$whereClause} ORDER BY usage_count DESC, created_at DESC LIMIT %d",
            ...$queryParams
        ), ARRAY_A);

        // 解析 steps JSON
        foreach ($rows ?: [] as &$row) {
            $row['steps'] = json_decode($row['steps'], true) ?: [];
        }

        return ToolResult::success(['recipes' => $rows ?: [], 'count' => count($rows ?: [])]);
    }

    /**
     * 获取单个配方
     */
    public static function get(array $params, int $userId): ToolResult
    {
        global $wpdb;
        $table = $wpdb->prefix . self::$table;
        $id = (int) ($params['id'] ?? 0);

        $row = $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM {$table} WHERE id = %d AND (author_id = %d OR is_public = 1)",
            $id, $userId
        ), ARRAY_A);

        if (!$row) return ToolResult::error('配方不存在或无权访问');

        $row['steps'] = json_decode($row['steps'], true) ?: [];
        return ToolResult::success(['recipe' => $row]);
    }

    /**
     * 更新配方
     */
    public static function update(array $params, int $userId): ToolResult
    {
        global $wpdb;
        $table = $wpdb->prefix . self::$table;
        $id = (int) ($params['id'] ?? 0);

        // 只能修改自己的
        $existing = $wpdb->get_var($wpdb->prepare(
            "SELECT author_id FROM {$table} WHERE id = %d", $id
        ));

        if (!$existing) return ToolResult::error('配方不存在');
        if ((int) $existing !== $userId) return ToolResult::error('只能修改自己的配方');

        $data = ['updated_at' => current_time('mysql')];
        if (isset($params['name'])) $data['name'] = $params['name'];
        if (isset($params['description'])) $data['description'] = $params['description'];
        if (isset($params['category'])) $data['category'] = $params['category'];
        if (isset($params['steps'])) $data['steps'] = json_encode($params['steps'], JSON_UNESCAPED_UNICODE);
        if (isset($params['is_public'])) $data['is_public'] = !empty($params['is_public']) ? 1 : 0;

        $wpdb->update($table, $data, ['id' => $id]);
        return ToolResult::success(['recipe_id' => $id, 'updated' => true]);
    }

    /**
     * 删除配方
     */
    public static function delete(array $params, int $userId): ToolResult
    {
        global $wpdb;
        $table = $wpdb->prefix . self::$table;
        $id = (int) ($params['id'] ?? 0);

        $existing = $wpdb->get_var($wpdb->prepare(
            "SELECT author_id FROM {$table} WHERE id = %d", $id
        ));

        if (!$existing) return ToolResult::error('配方不存在');
        if ((int) $existing !== $userId) return ToolResult::error('只能删除自己的配方');

        $wpdb->delete($table, ['id' => $id]);
        return ToolResult::success(['deleted' => true]);
    }

    /**
     * 执行配方 — 按步骤依次调用工具
     */
    public static function execute(array $params, int $userId): ToolResult
    {
        global $wpdb;
        $table = $wpdb->prefix . self::$table;
        $id = (int) ($params['id'] ?? 0);
        $targetPostId = (int) ($params['target_post_id'] ?? 0);

        $row = $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM {$table} WHERE id = %d AND (author_id = %d OR is_public = 1)",
            $id, $userId
        ), ARRAY_A);

        if (!$row) return ToolResult::error('配方不存在或无权访问');

        $steps = json_decode($row['steps'], true) ?: [];
        if (empty($steps)) return ToolResult::error('配方步骤为空');

        $registry = ToolRegistry::instance();
        $results = [];
        $successCount = 0;

        foreach ($steps as $i => $step) {
            $toolId = $step['tool_id'] ?? '';
            $stepParams = $step['params'] ?? [];

            // 注入目标文章ID
            if ($targetPostId && !isset($stepParams['post_id'])) {
                $stepParams['post_id'] = $targetPostId;
            }

            try {
                $result = $registry->execute($toolId, $stepParams, $userId);
                $results[] = [
                    'step'       => $i + 1,
                    'tool_id'    => $toolId,
                    'success'    => $result['success'] ?? false,
                    'message'    => $result['message'] ?? '',
                    'data'       => $result['data'] ?? null,
                ];
                if ($result['success'] ?? false) $successCount++;
            } catch (\Exception $e) {
                $results[] = [
                    'step'    => $i + 1,
                    'tool_id' => $toolId,
                    'success' => false,
                    'message' => $e->getMessage(),
                ];
            }
        }

        // 更新使用次数
        $wpdb->query($wpdb->prepare(
            "UPDATE {$table} SET usage_count = usage_count + 1 WHERE id = %d", $id
        ));

        return ToolResult::success([
            'recipe_name'   => $row['name'],
            'total_steps'   => count($steps),
            'success_count' => $successCount,
            'results'       => $results,
        ]);
    }

    /**
     * 获取预设模板（初始化时用）
     */
    public static function getPresets(): array
    {
        return [
            [
                'name'        => '新文章全流程',
                'description' => '生成标签→SEO→摘要→内链→润色',
                'category'    => 'content',
                'is_public'   => true,
                'steps'       => [
                    ['tool_id' => 'generate_tags', 'params' => ['mode' => 'ai']],
                    ['tool_id' => 'generate_seo', 'params' => []],
                    ['tool_id' => 'generate_summary', 'params' => []],
                    ['tool_id' => 'build_autolink', 'params' => []],
                    ['tool_id' => 'polish_content', 'params' => ['depth' => 'light']],
                ],
            ],
            [
                'name'        => 'SEO全优化',
                'description' => 'SEO标题→关键词→描述→结构化数据→推送搜索引擎',
                'category'    => 'seo',
                'is_public'   => true,
                'steps'       => [
                    ['tool_id' => 'generate_seo', 'params' => []],
                    ['tool_id' => 'generate_schema', 'params' => []],
                    ['tool_id' => 'push_search', 'params' => []],
                    ['tool_id' => 'score_seo', 'params' => []],
                ],
            ],
            [
                'name'        => 'AI快速写作',
                'description' => '生成大纲→写文章→生成封面',
                'category'    => 'content',
                'is_public'   => true,
                'steps'       => [
                    ['tool_id' => 'write_article', 'params' => ['status' => 'draft']],
                    ['tool_id' => 'generate_cover', 'params' => []],
                ],
            ],
            [
                'name'        => '内容精修',
                'description' => '深度润色→质量评分→错别字修复',
                'category'    => 'content',
                'is_public'   => true,
                'steps'       => [
                    ['tool_id' => 'polish_content', 'params' => ['depth' => 'deep']],
                    ['tool_id' => 'score_quality', 'params' => []],
                    ['tool_id' => 'fix_grammar', 'params' => []],
                ],
            ],
            [
                'name'        => '图片优化',
                'description' => '生成ALT文字→图片压缩→添加水印',
                'category'    => 'media',
                'is_public'   => true,
                'steps'       => [
                    ['tool_id' => 'generate_alt', 'params' => []],
                    ['tool_id' => 'compress_image', 'params' => []],
                    ['tool_id' => 'apply_watermark', 'params' => []],
                    ['tool_id' => 'convert_to_webp', 'params' => []],
                ],
            ],
        ];
    }

    /**
     * 初始化预设模板
     */
    public static function seedPresets(): void
    {
        global $wpdb;
        $table = $wpdb->prefix . self::$table;

        $existing = $wpdb->get_var("SELECT COUNT(*) FROM {$table}");
        if ($existing > 0) return;

        foreach (self::getPresets() as $preset) {
            $wpdb->insert($table, [
                'name'        => $preset['name'],
                'description' => $preset['description'],
                'category'    => $preset['category'],
                'steps'       => json_encode($preset['steps'], JSON_UNESCAPED_UNICODE),
                'author_id'  => 0,
                'is_public'   => 1,
                'usage_count' => 0,
                'created_at'  => current_time('mysql'),
                'updated_at'  => current_time('mysql'),
            ]);
        }
    }
}
