import { Injectable } from '@nestjs/common';
import { AiGatewayService } from '../gateway/ai-gateway.service';
import { LearningTrendResultSchema } from '../prompts/schemas/learning-trend.schema';
import type { LearningTrendResult } from '../prompts/schemas/learning-trend.schema';

export interface LearningTrendInput {
  userId: string;
  periodDays: number;
  totalMinutes: number;
  sessionsCount: number;
  activeRecallCount: number;
  reviewCount: number;
  aiAnalysisCount: number;
  completedLoopCount: number;
  activityLevel: number;
  activeDays: number;
  dailyAverage: number;
  previousPeriod?: {
    totalMinutes: number;
    activeRecallCount: number;
    reviewCount: number;
    activeDays: number;
  };
}

@Injectable()
export class LearningTrendWorkflow {
  constructor(private readonly gateway: AiGatewayService) {}

  async execute(input: LearningTrendInput): Promise<LearningTrendResult> {
    const prev = input.previousPeriod;
    const userMessage = [
      `【学习数据概览 — 最近 ${input.periodDays} 天】`,
      `总学习时长：${input.totalMinutes} 分钟`,
      `学习会话数：${input.sessionsCount} 次`,
      `主动回忆次数：${input.activeRecallCount} 次`,
      `复习卡片数：${input.reviewCount} 张`,
      `AI 分析次数：${input.aiAnalysisCount} 次`,
      `完成学习循环：${input.completedLoopCount} 次`,
      `活跃天数：${input.activeDays} 天`,
      `日均学习：${input.dailyAverage} 分钟`,
      `活跃度评分：${input.activityLevel}/10`,
      '',
      prev ? `【上一周期对比（${input.periodDays}天前）】` : '',
      prev ? `总时长：${prev.totalMinutes}分钟 | 主动回忆：${prev.activeRecallCount}次 | 复习：${prev.reviewCount}张 | 活跃天数：${prev.activeDays}天` : '',
      prev ? '' : '',
      `请根据以上数据生成学习趋势分析报告。`,
      prev ? '注意对比两个周期的变化趋势。' : '注意这是首次分析，没有历史对比数据，请关注绝对值和建议。',
    ].join('\n');

    const response = await this.gateway.generate({
      feature: 'learning-trend',
      userId: input.userId,
      tier: 'primary',
      promptKey: 'learning-trend',
      promptVersion: '1.0.0',
      messages: [
        { role: 'user', content: userMessage },
      ],
      outputSchema: LearningTrendResultSchema,
    });

    return response.parsed as unknown as LearningTrendResult;
  }
}
