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

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

/**
 * AI Form Designer endpoint
 * 
 * Accepts natural language instructions and current form fields/events,
 * calls an OpenAI-compatible LLM API to generate modified form fields and event scripts.
 * 
 * Reuses the same environment variables as /am/ai/design:
 *   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/form-design', 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 { fields, events, userRequest, images, instance_template, form_script, flow_events, chineseFieldNames, isUpgrade } = req.body;

    if (!userRequest) {
      return res.status(400).json({ error: '请输入需求描述' });
    }

    const systemPrompt = buildFormDesignSystemPrompt({ chineseFieldNames: !!chineseFieldNames, isUpgrade: !!isUpgrade });

    // Build current fields description
    const fieldsJson = JSON.stringify(fields || [], null, 2);
    const eventsJson = JSON.stringify(events || {}, null, 2);

    // Build extra data sections for upgrade scenario
    let extraSections = '';
    if (instance_template) {
      extraSections += `\n\n## 审批单模板 (instance_template)\n\`\`\`html\n${instance_template}\n\`\`\``;
    }
    if (form_script) {
      extraSections += `\n\n## 表单脚本 (form_script)\n\`\`\`javascript\n${form_script}\n\`\`\``;
    }
    if (flow_events) {
      extraSections += `\n\n## 流程事件 (flow_events)\n\`\`\`javascript\n${flow_events}\n\`\`\``;
    }

    const userContent = `## 当前表单字段
${fieldsJson}

## 当前事件脚本
${eventsJson}${extraSections}

## 用户需求
${userRequest}

请返回修改后的完整 JSON 对象（包含 tableColumns、fields 和 events）。`;

    // Build user message content: support multi-modal (text + images)
    let userMessageContent;
    if (Array.isArray(images) && images.length > 0) {
      // Multi-modal content array
      userMessageContent = [
        { type: 'text', text: userContent },
        ...images.slice(0, 5).map(img => ({
          type: 'image_url',
          image_url: { url: img, detail: 'auto' },
        })),
      ];
    } else {
      userMessageContent = userContent;
    }
    console.log('User message content:', JSON.stringify([
        { role: 'system', content: systemPrompt },
        { role: 'user', content: userMessageContent },
      ], null, 2));
    const response = await axios.post(`${baseURL}/chat/completions`, {
      model,
      messages: [
        { role: 'system', content: systemPrompt },
        { role: 'user', content: userMessageContent },
      ],
      temperature: 0.3,
      max_tokens: 16000,
    }, {
      headers: {
        'Authorization': `Bearer ${apiKey}`,
        'Content-Type': 'application/json',
      },
      timeout: 300000,
    });

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

    // Try to parse the JSON from the response
    let result;
    try {
      let text = content.trim();
      // Strip markdown code block if present
      if (text.startsWith('```json')) text = text.slice(7);
      else if (text.startsWith('```')) text = text.slice(3);
      if (text.endsWith('```')) text = text.slice(0, -3);
      text = text.trim();

      // Find JSON object
      const objStart = text.indexOf('{');
      const objEnd = text.lastIndexOf('}');
      if (objStart !== -1 && objEnd > objStart) {
        result = JSON.parse(text.substring(objStart, objEnd + 1));
      } else {
        result = JSON.parse(text);
      }
    } catch (parseErr) {
      return res.status(500).json({
        error: 'AI 返回内容无法解析为 JSON',
        raw: content,
      });
    }

    // Validate result structure
    if (!result || typeof result !== 'object') {
      return res.status(500).json({ error: 'AI 返回的不是有效的 JSON 对象' });
    }

    // Normalise: accept either { fields, events } or just an array (treat as fields)
    if (Array.isArray(result)) {
      result = { fields: result, events: events || {} };
    }

    // Ensure fields is an array
    if (result.fields && !Array.isArray(result.fields)) {
      return res.status(500).json({ error: 'AI 返回的 fields 不是数组' });
    }

    // Validate field types
    const validTypes = [
      'text', 'textarea', 'number', 'date', 'datetime', 'time',
      'select', 'multiSelect', 'checkbox', 'radio', 'file', 'image',
      'lookup', 'section', 'table', 'grid', 'formula',
      'member', 'memberMulti', 'org', 'orgMulti', 'reference', 'richtext'
    ];
    const jsIdentifierRe = /^[^\s{}][^{}]*$/;
    function sanitizeName(name) {
      if (!name) return 'field_' + Math.random().toString(36).slice(2, 6);
      // Only remove curly braces (reserved for formula variable references)
      let s = String(name).replace(/[{}]/g, '');
      return s.trim() || 'field_' + Math.random().toString(36).slice(2, 6);
    }

    if (result.fields) {
      for (const field of result.fields) {
        // Backward compat: map legacy userPicker/groupPicker to new types
        if (field.type === 'userPicker') field.type = field.pickerMultiple ? 'memberMulti' : 'member';
        if (field.type === 'groupPicker') field.type = field.pickerMultiple ? 'orgMulti' : 'org';
        // Backward compat: map legacy select + pickerMultiple to multiSelect
        if (field.type === 'select' && field.pickerMultiple) field.type = 'multiSelect';
        // Backward compat: map legacy html type to richtext
        if (field.type === 'html') field.type = 'richtext';
        if (field.type && !validTypes.includes(field.type)) {
          field.type = 'text'; // fallback to text for unknown types
        }
        // Validate/sanitize field name to be a valid JS identifier
        if (field.name && !jsIdentifierRe.test(field.name)) {
          field.name = sanitizeName(field.name);
        }
        // Remove colspan/tableColspan from AI output — layout is determined by field type defaults
        delete field.colspan;
        delete field.tableColspan;
        // Validate children types for table
        if (field.type === 'table' && Array.isArray(field.children)) {
          for (const child of field.children) {
            // Backward compat: map legacy types in children
            if (child.type === 'userPicker') child.type = child.pickerMultiple ? 'memberMulti' : 'member';
            if (child.type === 'groupPicker') child.type = child.pickerMultiple ? 'orgMulti' : 'org';
            if (child.type === 'select' && child.pickerMultiple) child.type = 'multiSelect';
            // Backward compat: map legacy html type to richtext
            if (child.type === 'html') child.type = 'richtext';
            if (child.type && !validTypes.includes(child.type)) {
              child.type = 'text';
            }
            // Validate/sanitize child field name
            if (child.name && !jsIdentifierRe.test(child.name)) {
              child.name = sanitizeName(child.name);
            }
            // Children cannot be section or table
            if (child.type === 'section' || child.type === 'table') {
              child.type = 'text';
            }
          }
        }
        // Validate children types for grid
        if (field.type === 'grid' && Array.isArray(field.children)) {
          for (const child of field.children) {
            // Backward compat: map legacy types in children
            if (child.type === 'userPicker') child.type = child.pickerMultiple ? 'memberMulti' : 'member';
            if (child.type === 'groupPicker') child.type = child.pickerMultiple ? 'orgMulti' : 'org';
            if (child.type === 'select' && child.pickerMultiple) child.type = 'multiSelect';
            if (child.type === 'html') child.type = 'richtext';
            if (child.type && !validTypes.includes(child.type)) {
              child.type = 'text';
            }
            if (child.name && !jsIdentifierRe.test(child.name)) {
              child.name = sanitizeName(child.name);
            }
            // Grid children cannot be section or grid
            if (child.type === 'section' || child.type === 'grid') {
              child.type = 'text';
            }
          }
        }
      }
    }

    // Ensure events is an object
    if (!result.events || typeof result.events !== 'object') {
      result.events = events || {};
    }

    // Build response
    const responseData = {
      fields: result.fields || fields || [],
      tableColumns: typeof result.tableColumns === 'number' ? result.tableColumns : undefined,
      events: {
        onInit: result.events.onInit || '',
        onValueChange: result.events.onValueChange || '',
        onSubmit: result.events.onSubmit || '',
      },
    };
    // Pass through migrationLog if present (for upgrade audit trail)
    if (Array.isArray(result.migrationLog) && result.migrationLog.length > 0) {
      responseData.migrationLog = result.migrationLog;
    }
    return res.json(responseData);

  } catch (error) {
    console.error('AI form design 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 密钥无效或权限不足，请检查 WORKFLOW_AI_API_KEY' });
      }
      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;
