import { Injectable } from '@nestjs/common';
import { HttpService } from '@nestjs/axios';
import { ConfigService } from '@nestjs/config';
import { AiConfigService } from './ai-config.service';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { AiConfig } from './ai-config.entity';
import { AiAdapterManager } from './ai-adapter.manager';

@Injectable()
export class AiService {
  private readonly defaultModel: string;
  private adapterManager!: AiAdapterManager;

  constructor(
    private readonly httpService: HttpService,
    private readonly configService: ConfigService,
    private readonly aiConfigService: AiConfigService,
    @InjectRepository(AiConfig)
    private aiConfigRepository: Repository<AiConfig>,
  ) {
    this.defaultModel = this.configService.get<string>('AI_DEFAULT_MODEL', 'gpt-3.5-turbo');
  }

  async initializeAdapterManager() {
    const configs = await this.aiConfigRepository.find();
    this.adapterManager = new AiAdapterManager(configs);
  }

  getAdapter(serviceId: string) {
    if (!this.adapterManager) {
      throw new Error('AI adapter manager not initialized');
    }
    return this.adapterManager.getAdapter(serviceId);
  }

  async generateCode(prompt: string, workspaceId: number) {
    // 获取工作区的AI配置
    const aiConfig = await this.aiConfigService.getAiConfigByWorkspace(workspaceId);
    
    // 这里实现调用外部AI服务的逻辑
    // 需要根据实际的AI服务API进行实现
    return {
      success: true,
      code: '// 生成的代码示例\nconsole.log("Hello World");',
      model: this.defaultModel,
    };
  }
}