const axios = require('axios');
const makeLinks = require('../../shared/hateoas');
const path = require('path');
const qs = require('qs');
const { v4: uuidv4 } = require('uuid');
require('dotenv').config({ path: path.resolve(__dirname, '../../.env') });
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';

exports.generate = async (req, res) => {
  const { prompt } = req.query;
  if (!prompt) {
    return res.status(400).json({ error: 'Prompt parameter is required' });
  }
  try {
    const apiKey = process.env.GIGACHAT_API_KEY;
    const tokenResp = await axios.post(
      'https://ngw.devices.sberbank.ru:9443/api/v2/oauth',
      {
        'scope':' GIGACHAT_API_PERS',
      },
      {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'Accept': 'application/json',
          'Authorization': `Basic ${apiKey}`,
          'RqUID':'6f0b1291-c7f3-43c6-bb2e-9f3efb2dc98e'
        },
      }
    );
    const accessToken = tokenResp.data.access_token;
    const chatResp = await axios.post(
      'https://gigachat.devices.sberbank.ru/api/v1/chat/completions',
      {
        model: "GigaChat",
        messages: [
          { role: "system", content: "Ты — Василий Кандинский" },
          { role: "user", content: prompt }
        ],
        stream: false,
        function_call: 'auto'
      },
      {
        headers: {
          'Authorization': `Bearer ${accessToken}`,
          'Content-Type': 'application/json',
          'RqUID': uuidv4(),
        }
      }
    );
    const content = chatResp.data.choices[0].message.content;
    const match = content.match(/<img src=\"(.*?)\"/);
    if (!match) {
      return res.status(500).json({ error: 'No image generated' });
    }
    const imageId = match[1];
    const imageResp = await axios.get(
      `https://gigachat.devices.sberbank.ru/api/v1/files/${imageId}/content`,
      {
        headers: {
          'Authorization': `Bearer ${accessToken}`,
          'RqUID': uuidv4(),
        },
        responseType: 'arraybuffer'
      }
    );
    res.set('Content-Type', 'image/jpeg');
    res.set('X-HATEOAS', JSON.stringify(makeLinks('/gigachat', { self: '/prompt' })));
    res.send(imageResp.data);
  } catch (err) {
    if (err.response) {
      console.error('AI生成图片出错:');
      console.error('status:', err.response.status);
      console.error('headers:', err.response.headers);
      console.error('data:', err.response.data);
      console.error('config:', err.config);
    } else {
      console.error('AI生成图片出错:', err.message);
    }
    res.status(500).json({ error: err.message });
  }
}; 