import path from "path";
import color from "picocolors";
import { createStepUI } from "../../utils/stepui.js";
import { title, getSteps } from "./config.js";
import { stopKeypress, waitForKey } from "../../keyboard.js";
import { buildTransforms, processFile } from "./service.js";

const run = async () => {
  const ui = createStepUI({ title, getSteps });
  const result = await ui.runInteractive();
  if (!result) return "back";

  stopKeypress();

  const config = {
    files: result.results[0] || [],
    commands: result.results[1] || [],
    quantizePreset: result.results[2] || "balanced",
    outputFormat: result.results[3] || "auto",
    outputOptions: result.results[4] || []
  };

  ui.showSummary([
    "模型文件: " + (config.files.length ? config.files.join(", ") : "未选择"),
    "gltf-transform 命令: " + (config.commands.length ? config.commands.join(", ") : "无"),
    "量化级别: " + config.quantizePreset,
    "输出格式: " + config.outputFormat,
    "输出选项: " + (config.outputOptions.length ? config.outputOptions.join(", ") : "默认")
  ]);

  if (!config.files.length) {
    console.log(color.yellow("未选择任何模型文件"));
    await waitForKey();
    return "back";
  }

  const transforms = buildTransforms(config);
  if (!transforms.length) {
    console.log(color.yellow("未配置任何压缩命令，请至少选择一项 gltf-transform 操作"));
    await waitForKey();
    return "back";
  }

  const total = config.files.length;
  let success = 0;
  const failed = [];

  console.log(color.cyan(`开始压缩 ${total} 个文件...\n`));

  for (let i = 0; i < config.files.length; i++) {
    const file = config.files[i];
    const progress = `[${i + 1}/${total}]`;
    console.log(color.dim(`${progress} 处理中: ${file}`));

    try {
      const result = await processFile(file, config, transforms);
      if (result.ok) {
        success++;
        console.log(color.green(`${progress} ✓ ${file} → ${path.basename(result.output)}`));
      } else {
        failed.push(file);
        console.log(color.yellow(`${progress} ⊘ 跳过: ${file}`));
      }
    } catch (err) {
      failed.push(file);
      console.log(color.red(`${progress} ✖ 失败: ${file}`));
      console.log(color.dim("   " + String(err?.message || err)));
    }
  }

  console.log("\n" + color.bgGreen(color.black(" 压缩完成 ")));
  if (success) console.log(color.green(`成功: ${success} 个`));
  if (failed.length) console.log(color.yellow(`失败: ${failed.length} 个 (${failed.join(", ")})`));

  await waitForKey();
  return "back";
};

export default {
  id: "model",
  name: "模型压缩",
  desc: "glTF/GLB/OBJ/FBX压缩",
  run,
};
