import { Request, Response } from 'express';
import { AIService } from '../../services/AIService';
import { PipelineEngine } from '../../core/pipeline/PipelineEngine';
import { logger } from '../../utils/logger';
import { StepStatus } from '../../core/pipeline/PipelineTypes';

/**
 * [UX_AUTO_01] AI 交互式指令台 (Command Center)
 * @description 将商户的自然语言指令转化为自治流水线任务
 */
export class CommandCenterController {
  /**
   * 语义解析并提交任务
   */
  static async submitNaturalCommand(req: Request, res: Response) {
    const { command } = req.body;
    const { tenantId, userId, traceId } = (req as any).traceContext;

    try {
      logger.info(`[CommandCenter] Parsing command: ${command}`);

      // 1. 调用 AI 进行语义解析 (Intent -> Pipeline Definition)
      const parsedPlan = await AIService.parseNaturalCommand(command);

      if (!parsedPlan || !parsedPlan.steps) {
        return res.status(400).json({ 
          success: false, 
          error: 'Could not understand your command. Please try again with more details.' 
        });
      }

      // 2. 向商户返回预览计划 (IAT 交互规范：需商户确认)
      if (req.query.preview === 'true') {
        return res.json({
          success: true,
          preview: parsedPlan,
          message: 'Plan parsed successfully. Please confirm execution.'
        });
      }

      // 3. 执行流水线
      const instanceId = await PipelineEngine.start({
        id: `IAT-CMD-${Date.now()}`,
        name: `Natural Language Command: ${command.substring(0, 30)}...`,
        steps: parsedPlan.steps.map((s: any) => ({
          ...s,
          status: StepStatus.PENDING
        }))
      }, {
        tenantId,
        shopId: parsedPlan.shopId || '',
        traceId,
        userId,
        variables: parsedPlan.variables || {}
      });

      res.json({
        success: true,
        data: {
          instanceId,
          plan: parsedPlan
        }
      });
    } catch (err: any) {
      logger.error(`[CommandCenter] Command submission failed: ${err.message}`);
      res.status(500).json({ success: false, error: err.message });
    }
  }

  /**
   * 获取正在运行的任务流预览
   */
  static async getActiveCommandStatus(req: Request, res: Response) {
    const { instanceId } = req.params;
    const status = await PipelineEngine.getInstanceStatus(instanceId as string);
    res.json({ success: true, data: status });
  }
}
