import fetch from 'node-fetch';
import cfg from './config.mjs';

const parseOutput = text => {
  text = text.trim().toLowerCase();
  return text.includes(', ')
    ? text.split(', ')
    : text.replace(/\d\. /g, '').split('\n');
};

export default new class autotagger {
  async isNSFW(filename, filesize) {
    let opts = {
      method: 'POST',
    };
    let apiurl;
    if(filesize < 4194304) {
      apiurl = cfg.apis.nsfw1.url;
      opts.headers = cfg.apis.nsfw1.headers;
      opts.body = JSON.stringify({
        DataRepresentation: "URL",
        Value: `${cfg.main.url.full}/b/${filename}`
      });
    }
    else {
      apiurl = cfg.apis.nsfw2.url;
      opts.headers = cfg.apis.nsfw2.headers;
      opts.body = JSON.stringify({
        url: `${cfg.main.url.full}/b/${filename}`
      })
    }
    const res = await (await fetch(apiurl, opts)).json();

    if(filesize < 4194304)
      return res.IsImageAdultClassified || res.RacyClassificationScore > 0.6;
    else
      return res.unsafe;
  };

  async getTags(id) {
    if(!id)
      return;

    try {
      const f0ck = `${cfg.main.url.full}/t/${id}.webp`;
      const blob = await (await fetch(f0ck)).arrayBuffer();

      const res = await fetch(`${cfg.apis.cf.url}/${cfg.apis.cf.id}/ai/run/${cfg.apis.cf.model}`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "Authorization": `Bearer ${cfg.apis.cf.key}`
        },
        body: JSON.stringify({
          image: [ ...new Uint8Array(blob) ],
          prompt: "Generate eight comma separated tags without colors for this image.",
          max_tokens: 128
        })
      });
      const json = await res.json();
      console.log(json.result.description);
      return parseOutput(json.result.description);
    } catch(err) {
      return {
        error: err.message || "unknown error"
      };
    }
  };
};
