#!/usr/bin/env node
import fs from "node:fs";
import os from "node:os";
import path from "node:path";

const defaultNotesRuntimeRoot = path.join(
  os.homedir(),
  "Library",
  "Application Support",
  "anime-fighter-pro-organizer",
  "runtime",
);
const defaultNotesRuntimeDb = path.join(defaultNotesRuntimeRoot, "data", "anime-fighter-pro-organizer.sqlite");

if (!process.env.SSB_ADMIN_DATA_ROOT && fs.existsSync(defaultNotesRuntimeDb)) {
  process.env.SSB_ADMIN_DATA_ROOT = defaultNotesRuntimeRoot;
}

function parseArgs(argv) {
  const [command, ...rest] = argv;
  const options = {
    command,
    all: false,
    character: "",
    rootDir: "",
    copyRefs: false,
    includePrototypes: false,
    approveUi: true,
    json: false,
  };

  for (let index = 0; index < rest.length; index += 1) {
    const value = rest[index];
    if (value === "--all") {
      options.all = true;
      continue;
    }
    if (value === "--copy-refs") {
      options.copyRefs = true;
      continue;
    }
    if (value === "--include-prototypes") {
      options.includePrototypes = true;
      continue;
    }
    if (value === "--pending-ui") {
      options.approveUi = false;
      continue;
    }
    if (value === "--json") {
      options.json = true;
      continue;
    }
    if (value === "--character") {
      options.character = rest[index + 1] || "";
      index += 1;
      continue;
    }
    if (value === "--root") {
      options.rootDir = rest[index + 1] || "";
      index += 1;
      continue;
    }
    throw new Error(`Unknown argument: ${value}`);
  }

  return options;
}

function printUsage() {
  console.log(`Usage:
  node scripts/sprite-pipeline.mjs export --all [--copy-refs]
  node scripts/sprite-pipeline.mjs export --character <slug> [--copy-refs]
  node scripts/sprite-pipeline.mjs validate --all
  node scripts/sprite-pipeline.mjs build-jobs --character <slug>
  node scripts/sprite-pipeline.mjs import --character <slug> [--pending-ui]
`);
}

function printResult(result, asJson) {
  if (asJson) {
    console.log(JSON.stringify(result, null, 2));
    return;
  }
  console.log(JSON.stringify(result, null, 2));
}

async function main() {
  try {
    const {
      buildSpriteJobs,
      exportSpritePackets,
      importSpriteOutputs,
      validateSpritePackets,
    } = await import("../src/sprite-pipeline.js");
    const options = parseArgs(process.argv.slice(2));
    let result;
    switch (options.command) {
      case "export":
        result = exportSpritePackets(options);
        break;
      case "validate":
        result = validateSpritePackets(options);
        break;
      case "build-jobs":
        result = buildSpriteJobs(options);
        break;
      case "import":
        result = importSpriteOutputs(options);
        break;
      case "help":
      case "--help":
      case "-h":
      case undefined:
        printUsage();
        process.exit(0);
      default:
        throw new Error(`Unknown command: ${options.command}`);
    }
    printResult(result, options.json);
  } catch (error) {
    console.error(error instanceof Error ? error.message : String(error));
    printUsage();
    process.exit(1);
  }
}

main();
