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 { record } from "../../stats.js";
import { processFile } from "./service.js";

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

  const config = {
    files: result.results[0] || [],
    outputFormat: result.results[1] || "glb2"
  };

  stopKeypress();
  ui.showSummary([
    "源文件: " + (config.files.length ? config.files.join(", ") : "未选择"),
    "目标格式: " + config.outputFormat.toUpperCase()
  ]);

  if (!config.files.length) {
    console.log(color.yellow("未选择任何模型文件"));
    await waitForKey(color.dim("按 Esc 返回"), key => key?.name === "escape" || (key?.ctrl && key?.name === "c"));
    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);
      if (result.ok) {
        success++;
        record("convert_format", config.outputFormat);
        console.log(color.green(`${progress} ✓ ${file} → ${path.basename(result.output)}`));
      } else {
        failed.push({ file, reason: result.reason });
        console.log(color.yellow(`${progress} ⊘ 跳过: ${file} (${result.reason})`));
      }
    } catch (err) {
      failed.push({ file, reason: err?.message || String(err) });
      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} 个`));

  await waitForKey(color.dim("按 Esc 返回"), key => key?.name === "escape" || (key?.ctrl && key?.name === "c"));
  return "back";
};

export default {
  id: "convert",
  name: "格式转换",
  desc: "支持多种模型格式转换",
  run,
};
