import Router from '@koa/router';
import { Context } from 'koa';
import axios from 'axios';
import { config } from '../../config';

const router = new Router();

// 免费优先的模型列表
const FREE_MODELS = [
  'tongyi-xiaomi-analysis-pro',
  'qwen3.5-122b-a10b',
  'qwen-plus',
];

// AI 生成文本
router.post('/generate', async (ctx: Context) => {
  const { prompt, model } = ctx.request.body as {
    prompt: string;
    model?: string;
  };

  if (!prompt || prompt.trim().length === 0) {
    ctx.status = 400;
    ctx.body = { code: 400, message: '请输入提示词' };
    return;
  }

  try {
    // 使用阿里云 DashScope API 调用 Qwen 大模型
    const apiKey = config.dashscope.apiKey;
    
    if (!apiKey) {
      ctx.status = 500;
      ctx.body = { code: 500, message: '未配置 AI API Key' };
      return;
    }

    // 优先使用指定的模型，否则使用免费的模型列表
    const selectedModel = model || FREE_MODELS[0];
    
    console.log(`🤖 使用模型: ${selectedModel}`);

    // 调用阿里云百炼文本生成 API
    const response = await axios.post(
      'https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation',
      {
        model: selectedModel,
        input: {
          prompt: prompt,
        },
        parameters: {
          result_format: 'message',
        },
      },
      {
        headers: {
          'Authorization': `Bearer ${apiKey}`,
          'Content-Type': 'application/json',
        },
        timeout: 60000,
      }
    );

    const data = response.data;
    console.log('🤖 AI 响应:', JSON.stringify(data));
    
    if (data.code) {
      throw new Error(data.message || `AI 调用失败: ${data.code}`);
    }

    // 提取生成的文本
    const generatedText = data.output?.choices?.[0]?.message?.content || '';
    
    ctx.body = {
      code: 0,
      message: 'success',
      data: {
        text: generatedText,
        model: selectedModel,
      },
    };
  } catch (error: any) {
    console.error('❌ AI 生成失败:', error.response?.data || error.message);
    ctx.status = 500;
    ctx.body = {
      code: 500,
      message: error.message || 'AI 生成失败，请稍后重试',
    };
  }
});

// 获取可用模型列表
router.get('/models', async (ctx: Context) => {
  ctx.body = {
    code: 0,
    message: 'success',
    data: {
      models: FREE_MODELS,
      default: FREE_MODELS[0],
    },
  };
});

export default router;
