<?php

namespace XZD\AI\V5\REST\Controllers;

use XZD\AI\V5\REST\BaseController;
use XZD\AI\V5\Core\Logger;
use WP_REST_Request;

/**
 * 操作日志 REST 端点
 *
 * GET  /logs      — 日志列表（筛选+分页）
 * GET  /logs/{id} — 日志详情
 * POST /logs/export — 导出CSV
 * POST /operations/{id}/undo — 撤销操作
 */
class LogController extends BaseController
{
    public function registerRoutes(): void
    {
        $this->registerGet('/logs', [$this, 'index'], 'manage_options');
        $this->registerGet('/logs/(?P<id>\d+)', [$this, 'show'], 'manage_options');
        $this->registerGet('/logs/export', [$this, 'export'], 'manage_options');
        $this->registerPost('/operations/(?P<id>\d+)/undo', [$this, 'undo'], 'manage_options');

        // 日志查阅是基础功能，不对免费版设限（已通过 manage_options 权限守卫）
    }

    public function index(WP_REST_Request $request): \WP_REST_Response
    {
        if ($err = $this->guardLicense('free')) return $err;
        $page    = $this->getIntParam($request, 'page', 1);
        $perPage = $this->getIntParam($request, 'per_page', 20);
        $status  = $this->getParam($request, 'status', '');
        $category = $this->getParam($request, 'category', '');
        $tab      = $this->getParam($request, 'tab', '');
        $search   = $this->getParam($request, 'search', '');
        $dateFrom = $this->getParam($request, 'date_from', '');
        $dateTo   = $this->getParam($request, 'date_to', '');
        $userId   = $this->getIntParam($request, 'user_id', 0);

        $filters = [];

        // TAB 预置筛选
        if ($tab) {
            switch ($tab) {
                case 'chat':
                    $filters['category'] = 'chat';
                    break;
                case 'tools':
                    // 排除 chat 和 automation
                    $filters['exclude_categories'] = ['chat', 'automation', 'pipeline'];
                    break;
                case 'pipeline':
                    $filters['category'] = 'pipeline';
                    break;
                case 'automation':
                    $filters['category'] = 'automation';
                    break;
                case 'error':
                    $filters['status'] = 'failed';
                    break;
                // 'all' — 不设筛选
            }
        } else {
            // 直接分类筛选
            if ($category && $category !== 'all') {
                $filters['category'] = $category;
            }
        }

        if ($status && $status !== 'all' && !isset($filters['status'])) {
            $filters['status'] = $status;
        }
        if ($search) {
            $filters['search'] = $search;
        }
        if ($dateFrom) {
            $filters['date_from'] = $dateFrom;
        }
        if ($dateTo) {
            $filters['date_to'] = $dateTo;
        }
        if ($userId > 0) {
            $filters['user_id'] = $userId;
        }

        $result = Logger::getLogs($filters, $page, min($perPage, 100));

        // 转换 items 为 logs 以兼容前端
        $logs = array_map(function ($item) {
            $item['params'] = json_decode($item['params'] ?? '{}', true);
            $item['result'] = json_decode($item['result'] ?? '{}', true);
            $item['undo_data'] = json_decode($item['undo_data'] ?? '{}', true);
            // 计算是否在撤销窗口内
            $item['can_undo'] = !$item['is_undone'] && $item['undo_data']
                && ($item['undo_window'] == 0 || (time() - strtotime($item['created_at'])) <= $item['undo_window']);
            // 操作员名称映射
            $uid = (int)($item['user_id'] ?? 0);
            if ($uid > 0) {
                $user = get_userdata($uid);
                $item['operator_name'] = $user ? $user->display_name : "用户#{$uid}";
            } else {
                $item['operator_name'] = '系统自动';
            }
            return $item;
        }, $result['items']);

        return $this->success([
            'logs'  => $logs,
            'total' => $result['total'],
            'page'  => $result['page'],
            'pages' => $result['pages'],
        ]);
    }

    public function show(WP_REST_Request $request): \WP_REST_Response
    {
        if ($err = $this->guardLicense('free')) return $err;
        $id = (int) $request->get_param('id');
        $log = Logger::getLog($id);

        if (!$log) {
            return $this->error('日志不存在', 'not_found', 404);
        }

        $log['params'] = json_decode($log['params'] ?? '{}', true);
        $log['result'] = json_decode($log['result'] ?? '{}', true);

        return $this->success($log);
    }

    public function export(WP_REST_Request $request): \WP_REST_Response
    {
        if ($err = $this->guardLicense('free')) return $err;
        $page   = $this->getIntParam($request, 'page', 1);
        $perPage = $this->getIntParam($request, 'per_page', 500);
        $status = $this->getParam($request, 'status', '');

        $filters = [];
        if ($status) {
            $filters['status'] = $status;
        }

        $result = Logger::getLogs($filters, $page, min($perPage, 1000));

        $csv = "id,时间,工具ID,工具名称,分类,目标类型,目标ID,状态,错误信息,用户ID,IP,耗时(ms),Token,费用\n";
        foreach ($result['items'] as $row) {
            $csv .= implode(',', [
                $row['id'] ?? '',
                $row['created_at'] ?? '',
                '"' . ($row['tool_id'] ?? '') . '"',
                '"' . ($row['tool_name'] ?? '') . '"',
                $row['category'] ?? '',
                $row['target_type'] ?? '',
                $row['target_id'] ?? '',
                $row['status'] ?? '',
                '"' . str_replace('"', '""', $row['error_message'] ?? '') . '"',
                $row['user_id'] ?? '',
                $row['ip'] ?? '',
                $row['duration_ms'] ?? '',
                $row['cost_tokens'] ?? '',
                $row['cost_rmb'] ?? '',
            ]) . "\n";
        }

        return $this->success([
            'csv' => $csv,
            'total' => $result['total'],
        ]);
    }

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

        $dispatcher = \XZD\AI\V5\Agents\ActionDispatcher::instance();
        $result = $dispatcher->undo($id, $userId);

        if ($result['success']) {
            return $this->success(null, $result['message']);
        }
        return $this->error($result['message'], 'undo_failed');
    }
}
