const express = require("express");
const router = express.Router();
const steedosAuth = require('@steedos/auth');
const axios = require('axios');
const bodyParser = require('body-parser');

router.use(bodyParser.json({ limit: '10mb' }));

/**
 * AI Code Generate endpoint
 * 
 * A lightweight endpoint for generating code snippets (formulas, event scripts, etc.)
 * using a custom system prompt provided by the client.
 * Unlike /am/ai/form-design, this does NOT inject any form-designer system prompt.
 * It returns the raw AI-generated text as { code: "..." }.
 *
 * Reuses the same environment variables:
 *   WORKFLOW_AI_API_KEY    - API key for the LLM provider
 *   WORKFLOW_AI_BASE_URL   - Base URL (default: https://api.openai.com/v1)
 *   WORKFLOW_AI_MODEL      - Model name (default: gpt-4o)
 */
router.post('/am/ai/code-generate', async function auth(req, res, next) {
  try {
    const result = await steedosAuth.auth(req, res);
    if (result && result.userId) {
      req.user = result;
      next();
    } else {
      res.status(401).json({ error: '请先登录' });
    }
  } catch (e) {
    res.status(401).json({ error: '认证失败' });
  }
}, async function (req, res) {
  try {
    const apiKey = process.env.WORKFLOW_AI_API_KEY;
    if (!apiKey) {
      return res.status(500).json({ error: '请先配置环境变量 WORKFLOW_AI_API_KEY' });
    }

    const baseURL = process.env.WORKFLOW_AI_BASE_URL || 'https://api.openai.com/v1';
    const model = process.env.WORKFLOW_AI_MODEL || 'gpt-4o';

    const { systemPrompt, userMessage } = req.body;

    if (!systemPrompt || !userMessage) {
      return res.status(400).json({ error: '缺少 systemPrompt 或 userMessage' });
    }
    console.log('User message content:', JSON.stringify([
        { role: 'system', content: systemPrompt },
        { role: 'user', content: userMessage },
      ], null, 2));
    const response = await axios.post(`${baseURL}/chat/completions`, {
      model,
      messages: [
        { role: 'system', content: systemPrompt },
        { role: 'user', content: userMessage },
      ],
      temperature: 0.3,
      max_tokens: 8000,
    }, {
      headers: {
        'Authorization': `Bearer ${apiKey}`,
        'Content-Type': 'application/json',
      },
      timeout: 120000,
    });

    const content = response.data?.choices?.[0]?.message?.content;
    if (!content) {
      return res.status(500).json({ error: 'AI 未返回有效内容' });
    }

    // Clean up: remove markdown code fences if present
    let code = content.trim();
    if (code.startsWith('```')) {
      // Remove opening fence (e.g. ```javascript, ```js, ```)
      code = code.replace(/^```[\w]*\n?/, '');
    }
    if (code.endsWith('```')) {
      code = code.slice(0, -3);
    }
    code = code.trim();

    return res.json({ code });

  } catch (error) {
    console.error('AI code generate error:', error?.response?.data || error?.message || error);
    if (error.response) {
      const status = error.response.status;
      const data = error.response.data;
      if (status === 401 || status === 403) {
        return res.status(500).json({ error: 'AI API 密钥无效或权限不足' });
      }
      if (status === 429) {
        return res.status(500).json({ error: 'AI API 请求频率超限，请稍后重试' });
      }
      return res.status(500).json({ error: data?.error?.message || 'AI API 调用失败' });
    }
    return res.status(500).json({ error: error.message || 'AI 服务调用失败' });
  }
});

exports.default = router;
