import { Controller, Post, Get, Body, Param, Optional } from '@nestjs/common';
import { ApiTags, ApiOperation } from '@nestjs/swagger';
import { AiAnalysisService } from './ai-analysis.service';
import { FeynmanExecutionRouter } from './feynman-execution-router';
import { CurrentUser } from '../../common/decorators/current-user.decorator';
import { AiAnalysisRateLimit } from '../../common/decorators/rate-limit.decorator';
import type { UserPayload } from '../../common/types';

@ApiTags('ai-analysis')
@Controller('ai-analysis')
export class AiAnalysisController {
  constructor(
    private readonly service: AiAnalysisService,
    @Optional() private readonly feynmanRouter?: FeynmanExecutionRouter,
  ) {}

  @Post()
  @AiAnalysisRateLimit()
  @ApiOperation({ summary: '提交主动回忆分析（异步）' })
  async analyze(
    @CurrentUser() user: UserPayload,
    @Body() body: {
      questionText: string;
      knowledgeItemContent: string;
      userAnswer: string;
      sessionId?: string;
      answerId?: string;
    },
  ) {
    return this.service.analyze(String(user?.id || 'anonymous'), body);
  }

  @Post('feynman')
  @AiAnalysisRateLimit()
  @ApiOperation({ summary: '提交费曼解释评估（异步）' })
  async evaluateFeynman(
    @CurrentUser() user: UserPayload,
    @Body() body: {
      knowledgeItemTitle: string;
      knowledgeItemContent: string;
      userExplanation: string;
      sessionId?: string;
      answerId?: string;
      knowledgeItemId?: string;
    },
  ) {
    const uid = String(user?.id || 'anonymous');

    // M-AI-05-05: 如果 FeynmanExecutionRouter 已注入，使用统一路由
    if (this.feynmanRouter) {
      return this.feynmanRouter.evaluateFeynman(uid, body, body.knowledgeItemId);
    }

    // 回退：Legacy 路径（兼容未导入 AiJobModule 的场景）
    return this.service.evaluateFeynman(uid, body);
  }

  @Get('jobs/:id')
  @ApiOperation({ summary: '查询 AI 分析任务状态' })
  async getJobStatus(@Param('id') id: string) {
    return this.service.getJobStatus(id);
  }

  @Get(':id')
  @ApiOperation({ summary: '获取分析结果' })
  async findOne(@Param('id') id: string) {
    return this.service.getResult(id);
  }
}
