import { Injectable, Logger } from '@nestjs/common';
import { PrismaService } from '@core/database/prisma/prisma.service';
import { UpdateConfigDto } from '../dto';

/**
 * AI 配置服务
 */
@Injectable()
export class AIConfigService {
  private readonly logger = new Logger(AIConfigService.name);

  constructor(private readonly prisma: PrismaService) {}

  /**
   * 获取所有配置
   */
  async findAll() {
    const configs = await this.prisma.aIConfiguration.findMany({
      where: { isActive: true },
      orderBy: [{ category: 'asc' }, { key: 'asc' }],
    });

    return configs.map((c) => ({
      id: c.id,
      key: c.key,
      value: c.value,
      category: c.category,
      isActive: c.isActive,
      updatedAt: c.updatedAt,
    }));
  }

  /**
   * 获取单个配置
   */
  async findOne(key: string, category: string = 'GENERAL') {
    const config = await this.prisma.aIConfiguration.findFirst({
      where: { key, category },
    });

    if (!config) {
      return null;
    }

    return {
      id: config.id,
      key: config.key,
      value: config.value,
      category: config.category,
      isActive: config.isActive,
      updatedAt: config.updatedAt,
    };
  }

  /**
   * 更新配置
   */
  async update(key: string, dto: UpdateConfigDto) {
    const category = dto.category || 'GENERAL';

    // 使用 upsert 确保配置存在
    const config = await this.prisma.aIConfiguration.upsert({
      where: {
        key_category: { key, category },
      },
      update: {
        value: dto.value,
      },
      create: {
        key,
        value: dto.value,
        category,
        isActive: true,
      },
    });

    this.logger.log(`更新配置: ${key} (${category})`);

    return {
      key: config.key,
      value: config.value,
      category: config.category,
      updatedAt: config.updatedAt,
    };
  }

  /**
   * 获取模型配置
   */
  async getModelConfig(): Promise<ModelConfig> {
    const [model, temperature, maxTokens] = await Promise.all([
      this.findOne('model'),
      this.findOne('temperature'),
      this.findOne('max_tokens'),
    ]);

    return {
      model: model?.value || 'gpt-4-turbo',
      temperature: parseFloat(temperature?.value || '0.7'),
      maxTokens: parseInt(maxTokens?.value || '2048', 10),
    };
  }
}

interface ModelConfig {
  model: string;
  temperature: number;
  maxTokens: number;
}
