import color from "picocolors";
import { checkToktx, scanImages, compressAll } from "./compressor.js";
import { runInteractive, showSummary } from "./ui.js";
import { runGltfExtension } from "./gltf.js";
import { stopKeypress, waitForKey } from "../keyboard.js";

export async function run() {
  checkToktx();
  const result = await runInteractive();
  if (!result) return "back";

  stopKeypress();

  const { results } = result;
  const [exts, quality, encoding, mipmap, outputOpts] = results;
  const config = { exts, quality, encoding, mipmap, outputOpts };
  showSummary([
    "文件格式: " + config.exts.join(", "),
    "压缩程度: " + config.quality,
    "编码格式: " + config.encoding,
    "Mipmap: " + config.mipmap,
    "输出选项: " + config.outputOpts.join(", ")
  ]);

  const { images, cwd } = scanImages(exts);
  if (images.length === 0) {
    console.log(color.yellow("当前目录没有匹配的图片"));
    await waitForKey();
    return "back";
  }

  console.log("📁 找到 " + color.cyan(images.length) + " 个待转换文件\n");
  const { total, failed } = await compressAll(images, config, cwd);

  if (failed > 0) {
    console.log(color.yellow("\n⚠️ 完成，但有 " + failed + " 个文件失败"));
  } else {
    console.log(color.green("\n🎉 全部文件压缩完成！"));
  }

  if (outputOpts.includes("gltfExtension")) {
    console.log(color.cyan("\n正在修改 glTF 文件..."));
    const { success, count } = runGltfExtension();
    if (success) console.log(color.green("✓ 已修改 " + count + " 个 glTF 文件"));
  }

  await waitForKey();
  return "back";
}
