import { Injectable, NotFoundException } from '@nestjs/common';
import { AiAnalysisRepository } from './ai-analysis.repository';
import { QueueService } from '../../infrastructure/queue/queue.service';

@Injectable()
export class AiAnalysisService {
  constructor(
    private readonly repository: AiAnalysisRepository,
    private readonly queue: QueueService,
  ) {}

  async analyze(userId: string, input: {
    questionText: string;
    knowledgeItemContent: string;
    userAnswer: string;
    sessionId?: string;
    answerId?: string;
  }) {
    const job = await this.repository.createJob(userId, 'active-recall', input.sessionId, input.answerId);

    await this.queue.add('ai-analysis', {
      jobId: job.id,
      userId,
      type: 'active-recall',
      questionText: input.questionText,
      knowledgeItemContent: input.knowledgeItemContent,
      userAnswer: input.userAnswer,
    });

    return { jobId: job.id, status: 'queued' };
  }

  async evaluateFeynman(userId: string, input: {
    knowledgeItemTitle: string;
    knowledgeItemContent: string;
    userExplanation: string;
    sessionId?: string;
    answerId?: string;
  }) {
    const job = await this.repository.createJob(userId, 'feynman-evaluation', input.sessionId, input.answerId);

    await this.queue.add('ai-analysis', {
      jobId: job.id,
      userId,
      type: 'feynman-evaluation',
      knowledgeItemTitle: input.knowledgeItemTitle,
      knowledgeItemContent: input.knowledgeItemContent,
      userExplanation: input.userExplanation,
    });

    return { jobId: job.id, status: 'queued' };
  }

  async getJobStatus(id: string) {
    const job = await this.repository.findJobById(id);
    if (!job) throw new NotFoundException('任务不存在');
    return {
      id: job.id,
      type: job.jobType,
      status: job.status,
      queuedAt: job.queuedAt,
      startedAt: job.startedAt,
      completedAt: job.finishedAt,
      errorMessage: job.internalErrorMessage,
      results: job.results,
    };
  }

  async getResult(id: string) {
    return this.repository.findResultById(id);
  }
}
