
var request = require('request');
const axios = require("axios")
const { response } = require('express');
const { Configuration, OpenAIApi } = require("openai");
const chatGPTKey = "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"

const configuration = new Configuration({
    apiKey: chatGPTKey
  });
const openai = new OpenAIApi(configuration);

async function chatTest(responseData) {
    var contentChat = responseData.webhook_event.body;
  if (contentChat.indexOf("[toall]") < 0) {
    var indexPicStart = contentChat.indexOf("image:");
    if (indexPicStart >=0) {
      //photo gener
      var promptText = contentChat.substring(indexPicStart + "image:".length, contentChat.length);
      console.log("prompt: "+ promptText);

      axios.post("https://api.openai.com/v1/images/generations", {
        prompt: promptText,
        n: 1,
        size: "512x512"
      },
      {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': "Bearer " + chatGPTKey,
        }
      }
      ).then(function(response) {
        console.log(response.data.data[0].url)
        chatmessage(responseData.webhook_event.room_id, responseData.webhook_event.from_account_id,
          responseData.webhook_event.message_id, response.data.data[0].url);  
      }).catch(function(error) {
        console.log(error)
      });

    } else {
      //chat
      var indexStart = contentChat.indexOf("[info]");
      var indexEnd = contentChat.indexOf("[/info]");
    var chatText = "";
      if (indexStart >= 0) {
        chatText = contentChat.substring(indexStart + "[info]".length, indexEnd);
      } else {
        chatText = contentChat.replace("[To:10088310][BSV] brave Assistant Bot","").replace("[To:10088310][BSV] brave Assistant Bot","");
      }
      console.log("Chat text: "+ chatText);
        const chatCompletion = await openai.createChatCompletion({
          model: "o3-mini-2025-01-31", //Set model ChatGPT
          messages: [{role: "user", content: chatText.trim()}],
        });
        chatmessage(responseData.webhook_event.room_id, responseData.webhook_event.from_account_id,
          responseData.webhook_event.message_id, chatCompletion.data.choices[0].message.content);  
    }
  }
  }

  async function test() {
    const chatCompletion = await openai.createChatCompletion({
      model: "o3-mini-2025-01-31",
      messages: [{role: "user", content: "Hello"}],
    });

    console.log("Chat text: "+ chatCompletion.data);
  }

  function chatmessage( _togroup, _touser,_messageid, _message){
    var formData = {
      // Pass a simple key-value pair
      body: "[rp aid="+_touser+" to="+_togroup+"-"+_messageid+"]\n"+_message
    }

    var _options = {
      method: 'POST',
      url: "https://api.chatwork.com/v2/rooms/"+_togroup+"/messages",
      formData: formData,
      headers: {
        'X-ChatWorkToken': '6f65b2cde85b3bb06dece173dc94d8cd', //Key chatwork
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    };

    request(_options, function(error, response, body){
      if (!error) {
        //var info = JSON.parse(body);
        console.log(body);
      }else{
        console.log(error);
      }
    });
}

function chatmessageTO( _togroup, formData ){  
var _options = {
method: 'POST',
url: "https://api.chatwork.com/v2/rooms/"+_togroup+"/messages",
formData: formData,
headers: {
'X-ChatWorkToken': '6f65b2cde85b3bb06dece173dc94d8cd',
'Content-Type': 'application/x-www-form-urlencoded'
}
};

request(_options, function(error, response, body){
if (!error) {
//var info = JSON.parse(body);
console.log(body);
}else{
console.log(error);
}
});
}


module.exports = function(app) {
    app.get('/', function(req, res, next){
      test()
        res.status(200).send({ success: true, message: 'success', data: "Welcome!"});
    });
    app.post('/test', async function(req, res, next) {
      var responseData = {
        "webhook_setting_id" : req.body.webhook_setting_id,
        "webhook_event_type" : req.body.webhook_event_type,
        "webhook_event_time" : req.body.webhook_event_time,
        "webhook_event" : req.body.webhook_event,
    }
    var contentChat = responseData.webhook_event.body;
    var indexStart = contentChat.indexOf("[info]") + "[info]".length;
    var indexEnd = contentChat.indexOf("[/info]");
    var contentQuestion = contentChat.substring(indexStart, indexEnd);
    res.status(200).send({ success: true, message: 'success', data: "content :" + contentQuestion});
  });

  app.post('/user', function(req, res, next){
                var responseData = {
                    "webhook_setting_id" : req.body.webhook_setting_id,
                    "webhook_event_type" : req.body.webhook_event_type,
                    "webhook_event_time" : req.body.webhook_event_time,
                    "webhook_event" : req.body.webhook_event,
                }
                chatTest(responseData);
    
                res.status(200).send({ success: true, message: 'success', data: req.body.webhook_event});
        });

}
  
    