import fs from "fs";
import path from "path";
import color from "picocolors";
import { checkRequiredFiles, modifyGltfContent, listGltfFiles, BACKUP_SUFFIX } from "../utils/gltf.js";
import { runInteractive, showSummary } from "./ui.js";
import { stopKeypress, waitForKey } from "../keyboard.js";

export function runGltfExtension(config = { files: [], extensions: ["textureBasisu"] }) {
  const cwd = process.cwd();
  const { files = [], extensions = ["textureBasisu"] } = config;
  const selectedExtensions = extensions.length ? extensions : ["textureBasisu"];

  const { ok, missing } = checkRequiredFiles();
  if (!ok) {
    console.log(color.red("\n✖ 缺少必要文件: " + missing.join(", ")));
    console.log(color.dim("请确保当前目录包含 .ktx2、.gltf 和 .bin 文件\n"));
    return { success: false, count: 0 };
  }

  const fallbackFiles = listGltfFiles();
  const gltfFiles = (files.length ? files : fallbackFiles).filter(f => f.toLowerCase().endsWith(".gltf"));
  if (!gltfFiles.length) {
    console.log(color.yellow("未选择可处理的 glTF 文件"));
    return { success: false, count: 0 };
  }

  let count = 0;

  for (const file of gltfFiles) {
    const fullPath = path.join(cwd, file);
    if (!fs.existsSync(fullPath)) {
      console.log(color.yellow("跳过缺失的文件: " + file));
      continue;
    }
    const baseName = file.replace(/\.gltf$/i, "");
    const backupName = baseName + BACKUP_SUFFIX + ".gltf";
    const backupPath = path.join(cwd, backupName);

    fs.copyFileSync(fullPath, backupPath);
    const modified = modifyGltfContent(fullPath, selectedExtensions);
    fs.writeFileSync(fullPath, JSON.stringify(modified, null, 2), "utf-8");
    console.log(color.green("✓ " + file + " (备份: " + backupName + ")"));
    count++;
  }

  return { success: count > 0, count };
}

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

  stopKeypress();

  const { results } = result;
  const config = {
    files: results[0] || [],
    extensions: results[1] || []
  };

  showSummary([
    "处理文件: " + (config.files.length ? config.files.join(", ") : "未选择"),
    "扩展选项: " + (config.extensions.length ? config.extensions.join(", ") : "未选择")
  ]);

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

  await waitForKey();
  return "back";
}
