import { copyFileSync, existsSync, mkdirSync } from "node:fs";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { spawnSync } from "node:child_process";

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const repoRoot = resolve(__dirname, "..");

const sourceDir = resolve(repoRoot, "dist/vendor");
const sourceFiles = ["gnommoplayer.js", "gnommoplayer.css"];

const targets = {
  editor: resolve(repoRoot, "../gnommoeditor/src/vendor/gnommoplayer"),
  web: resolve(repoRoot, "../gnommoweb/src/vendor/gnommoplayer"),
};

function printUsage() {
  console.log(`Usage:
  node scripts/deploy-vendor.mjs <editor|web|all> [--skip-build]

Examples:
  node scripts/deploy-vendor.mjs editor
  node scripts/deploy-vendor.mjs web
  node scripts/deploy-vendor.mjs all
  node scripts/deploy-vendor.mjs all --skip-build`);
}

function ensureBuild() {
  const result = spawnSync("npm", ["run", "build:lib"], {
    cwd: repoRoot,
    stdio: "inherit",
    shell: process.platform === "win32",
  });

  if (result.status !== 0) {
    process.exit(result.status ?? 1);
  }
}

function ensureArtifactsExist() {
  for (const fileName of sourceFiles) {
    const filePath = resolve(sourceDir, fileName);
    if (!existsSync(filePath)) {
      console.error(`Missing build artifact: ${filePath}`);
      console.error("Run `npm run build:lib` first or omit `--skip-build`.");
      process.exit(1);
    }
  }
}

function deployTarget(targetName) {
  const destinationDir = targets[targetName];

  mkdirSync(destinationDir, { recursive: true });

  for (const fileName of sourceFiles) {
    copyFileSync(resolve(sourceDir, fileName), resolve(destinationDir, fileName));
  }

  console.log(`Deployed GlitchPlayer vendor bundle to ${targetName}:`);
  console.log(`  ${destinationDir}`);
}

const args = process.argv.slice(2);
const shouldSkipBuild = args.includes("--skip-build");
const filteredArgs = args.filter((arg) => arg !== "--skip-build");
const requestedTarget = filteredArgs[0] ?? "all";

if (requestedTarget === "--help" || requestedTarget === "-h") {
  printUsage();
  process.exit(0);
}

const selectedTargets =
  requestedTarget === "all"
    ? Object.keys(targets)
    : requestedTarget in targets
      ? [requestedTarget]
      : null;

if (!selectedTargets) {
  console.error(`Unknown deployment target: ${requestedTarget}`);
  printUsage();
  process.exit(1);
}

if (!shouldSkipBuild) {
  ensureBuild();
}

ensureArtifactsExist();

for (const targetName of selectedTargets) {
  deployTarget(targetName);
}
