import { Injectable, Logger } from '@nestjs/common';
import { AiGatewayService } from '../ai/gateway/ai-gateway.service';
import { LearningAnalysisResultSchema } from '../ai/prompts/schemas/learning-analysis.schema';
import type { LearningAnalysisSnapshot } from './learning-analysis-snapshot-builder';

@Injectable()
export class LearningAnalysisExecutor {
  private readonly logger = new Logger(LearningAnalysisExecutor.name);
  constructor(private readonly aiGateway: AiGatewayService) {}

  async execute(snapshot: LearningAnalysisSnapshot, timeoutMs: number) {
    const s = snapshot.snapshot;

    const userMessage = [
      `【学习数据摘要】`,
      `学习时长：${s.studyMetrics.totalStudyDuration}秒，活跃${s.studyMetrics.activeDays}天`,
      `复习完成：${s.reviewMetrics.reviewCompletedCount}次，准确率：${Math.round(s.reviewMetrics.reviewAccuracy * 100)}%`,
      `测验完成：${s.quizMetrics.attemptCount}次，准确率：${Math.round(s.quizMetrics.accuracy * 100)}%`,
      `主动回忆：${s.activeRecallMetrics.count}次，平均分：${s.activeRecallMetrics.avgScore}`,
      `费曼练习：${s.feynmanMetrics.count}次，薄弱点：${s.feynmanMetrics.weaknessCount}个`,
      `知识点进度：${s.knowledgeProgress.totalItems}个知识点`,
      s.knowledgeProgress.weakItems.length > 0
        ? `薄弱知识点：${s.knowledgeProgress.weakItems.map(i => i.title).join('、')}`
        : '',
      '',
      `数据质量：${s.dataQuality.availableSources.join(', ')} 可用`,
      s.dataQuality.insufficientDataReasons.length > 0
        ? `注意：${s.dataQuality.insufficientDataReasons.join('；')}`
        : '',
    ].filter(Boolean).join('\n');

    this.logger.log(
      `Learning Analysis Executor calling AI: userId=${s.userId} ` +
      `modelTier=${s.modelTier} timeoutMs=${timeoutMs}`,
    );

    const response = await this.aiGateway.generate(
      {
        feature: 'learning-analysis',
        userId: s.userId,
        tier: s.modelTier as any,
        promptKey: s.promptKey,
        promptVersion: s.promptVersion,
        messages: [{ role: 'user' as const, content: userMessage }],
        outputSchema: LearningAnalysisResultSchema,
        maxTokens: 4096,
      },
      timeoutMs,
    );

    this.logger.log(
      `Learning Analysis Executor completed: userId=${s.userId} ` +
      `strengths=${(response.parsed as any)?.strengths?.length} ` +
      `recommendations=${(response.parsed as any)?.recommendations?.length} ` +
      `confidence=${(response.parsed as any)?.confidence}`,
    );

    return response;
  }
}
