import { exec } from "child_process";
import fs from "fs";
import path from "path";
import https from "https";
import http from "http";

// Função para rodar comandos de shell
function runCmd(cmd) {
  return new Promise((resolve, reject) => {
    const p = exec(cmd, (err, stdout, stderr) => {
      if (err) return reject(err);
      resolve({ stdout, stderr });
    });
    p.stdout.pipe(process.stdout);
    p.stderr.pipe(process.stderr);
  });
}

// Função para baixar arquivo
function downloadFile(url, dest) {
  return new Promise((resolve, reject) => {
    if (fs.existsSync(dest)) {
      console.log(`${dest} já existe, pulando download.`);
      return resolve();
    }

    console.log(`Baixando ${url} → ${dest}`);
    const file = fs.createWriteStream(dest);
    const client = url.startsWith("https") ? https : http;

    client.get(url, (res) => {
      if (res.statusCode >= 400) return reject(new Error(`Erro ao baixar ${url}: ${res.statusCode}`));
      res.pipe(file);
      file.on("finish", () => file.close(resolve));
    }).on("error", (err) => {
      fs.unlink(dest, () => reject(err));
    });
  });
}

async function main() {
  // setup do npm
  await runCmd("npm ci");

  // cria pasta para binários
  const binDir = path.resolve("bin");
  if (!fs.existsSync(binDir)) fs.mkdirSync(binDir, { recursive: true });

  // downloads
  const files = [
    ["https://github.com/synt-xerror/manybot/releases/download/dependencies/yt-dlp.exe", "yt-dlp.exe"],
    ["https://github.com/synt-xerror/manybot/releases/download/dependencies/yt-dlp.exe", "yt-dlp"],
    ["https://github.com/synt-xerror/manybot/releases/download/dependencies/yt-dlp.exe", "ffmpeg.exe"],
    ["https://github.com/synt-xerror/manybot/releases/download/dependencies/yt-dlp.exe", "ffmpeg"]
  ];

  for (const [url, name] of files) {
    await downloadFile(url, path.join(binDir, name));
  }

  console.log("Setup concluído.");
}

main().catch(console.error);