const models = require('../models');
const fetch = require('node-fetch');
const fs = require('fs');

const { tags } = require('../config/tag');

let apiKey = require('process').env.ARK_API_KEY;
const url = "https://ark.cn-beijing.volces.com/api/v3/chat/completions";
let headers = {
  'Authorization': `Bearer ${apiKey}`,
  'Content-Type': 'application/json'
}

/**
 * 豆包对话API
 * @param {*} text 
 */
async function fetchMetaByTxtFromDoubao(text) {
  let data = {
    "model": "ep-20250206115552-7qg5c", // Doubao-1.5...ion-pro-32k 当前最新，贵，响应慢，效果好
    // "model": "ep-20250204231910-4phb8", // Doubao-vision-lite-32k  便宜点，相应速度快
    "messages": [
      { "role": "user", "content": text }
    ]
  }

  console.log(data);

  const jsonData = JSON.stringify(data);

  const response = await fetch(url, { method: 'POST', headers, body: jsonData });

  let responseJson = await response.json();

  console.log(responseJson);

  return responseJson.choices[0].message.content;
}


async function runTagMetaToDB() {
  let done = 0;
  let duration = 0;
  let hour, minute, second;
  let start = Date.now();

  let total = tags.length;
  console.log('total:', total);
  if (total <= 0) return;

  for (let tag of tags) {
    console.log(`process tag ${tag.tag}`);

    console.time(tag.tag);

    let doc = await models.TagSeo.findOne({ tag: tag.tag });
    if (!doc) {
      doc = new models.TagSeo({ tag: tag.tag });
    } else {
      console.log(`已经有${tag.tag}的seo信息，直接跳过`);
      continue;
    }

    try {
      let text = `生成 ${tag.tag} coloring pages 的SEO title(60个字符以内) 和 description(160个字符以内), 以json格式输出，支持语言中文(zh)、英语(en)、西班牙语(es)、葡萄牙语(pt)、日语(ja)，形如： { title: {zh:'', en:'', es: '', pt: '', ja: ''}, description: {zh:'', en:'', es: '', pt: '', ja: ''}`;
      let metaInfo = await fetchMetaByTxtFromDoubao(text);
      console.log(metaInfo);
      let metaInfoJson = JSON.parse(metaInfo);
      let titleJson = metaInfoJson.title;
      let descJson = metaInfoJson.description;
      let title = JSON.stringify(titleJson);
      let desc = JSON.stringify(descJson);


      doc.seoTitle = title;
      doc.seoDescription = desc;
      await doc.save();

    } catch (e) {
      console.error(e.message);
    }

    console.timeEnd(tag.tag);

    done++;
    duration = (Date.now() - start) / 1000;
    hour = (Math.floor(duration / 60 / 60)).toString().padStart(2, '0');
    minute = (Math.floor(duration / 60) % 60).toString().padStart(2, '0');
    second = (Math.floor(duration) % 60).toString().padStart(2, '0');

    console.log('progress: ' + Math.floor((100 * done / total)) + '% used time: ' + hour + ':' + minute + ':' + second);

  }
}

async function runTagMetaToFile() {
  let done = 0;
  let duration = 0;
  let hour, minute, second;
  let start = Date.now();

  let total = tags.length;
  console.log('total:', total);
  if (total <= 0) return;

  for (let tag of tags) {
    console.log(`process tag ${tag.tag}`);

    console.time(tag.tag);

    if (tag.seoTitle.en.length > 0) {
      console.log(`已经有${tag.tag}的seo信息，直接跳过`);
      continue;
    }


    try {
      let text = `生成 ${tag.title.en} Coloring Pages 的SEO title(60个字符以内) 和 description(160个字符以内), 以json格式输出，支持语言中文(zh)、英语(en)、西班牙语(es)、葡萄牙语(pt)、日语(ja)，形如： { title: {zh:'', en:'', es: '', pt: '', ja: ''}, description: {zh:'', en:'', es: '', pt: '', ja: ''}`;
      let metaInfo = await fetchMetaByTxtFromDoubao(text);
      console.log(metaInfo);

      let metaInfoJson = JSON.parse(metaInfo);
      tag.seoTitle = metaInfoJson.title;
      tag.seoDescription = metaInfoJson.description;;

    } catch (e) {
      console.error(e.message);
    }

    // write to file
    let text = JSON.stringify(tags);
    fs.writeFileSync('tags.json', text);

    console.timeEnd(tag.tag);

    done++;
    duration = (Date.now() - start) / 1000;
    hour = (Math.floor(duration / 60 / 60)).toString().padStart(2, '0');
    minute = (Math.floor(duration / 60) % 60).toString().padStart(2, '0');
    second = (Math.floor(duration) % 60).toString().padStart(2, '0');

    console.log('progress: ' + Math.floor((100 * done / total)) + '% used time: ' + hour + ':' + minute + ':' + second);

  }
}



async function run() {
  await runTagMetaToFile();
}


async function test() {
  let metaInfo = await fetchMetaByImageFromDoubao("https://color.jccytech.cn/thumbs/v2/work/640/67a254ec4f9d65537938e5c5.png");
  console.log(metaInfo);
  let metaInfoJson = JSON.parse(metaInfo);
  let titleJson = metaInfoJson.title;
  let descJson = metaInfoJson.copy;
  let title = JSON.stringify(titleJson);
  let desc = JSON.stringify(descJson);
  console.log(title);
  console.log(desc);
}


module.exports = { run }


if (require.main == module) {
  run();
}
