import { cp, lstat, mkdir } from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";

const repositoryRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const sourceRoot = path.join(repositoryRoot, "game_assets");
const runtimeRoot = path.join(repositoryRoot, "src", "assets", "game");
const [assetPath, ...options] = process.argv.slice(2);
const replace = options.includes("--replace");

if (!assetPath || options.some((option) => option !== "--replace")) {
  console.error("Usage: pnpm assets:import <path-within-game_assets> [--replace]");
  process.exit(1);
}

const normalizedAssetPath = path.normalize(assetPath);
if (path.isAbsolute(normalizedAssetPath) || normalizedAssetPath === "." || normalizedAssetPath === ".." || normalizedAssetPath.startsWith(`..${path.sep}`)) {
  console.error("Asset path must stay within game_assets.");
  process.exit(1);
}

const sourcePath = path.join(sourceRoot, normalizedAssetPath);
const runtimePath = path.join(runtimeRoot, normalizedAssetPath);

try {
  const source = await lstat(sourcePath);
  await mkdir(path.dirname(runtimePath), { recursive: true });
  await cp(sourcePath, runtimePath, { recursive: source.isDirectory(), errorOnExist: !replace, force: replace });
  console.log(`Imported ${path.relative(repositoryRoot, sourcePath)} -> ${path.relative(repositoryRoot, runtimePath)}`);
} catch (error) {
  const message = error instanceof Error ? error.message : String(error);
  console.error(`Could not import ${assetPath}: ${message}`);
  process.exit(1);
}
