"use strict";

const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");

const REPO_ROOT = path.resolve(__dirname, "..");
const TEMPLATE_DIR = path.join(REPO_ROOT, "themes", "template");

function slugifyThemeId(input) {
  return String(input || "")
    .trim()
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-+|-+$/g, "") || "my-theme";
}

function humanizeThemeId(themeId) {
  return String(themeId || "my-theme")
    .split("-")
    .filter(Boolean)
    .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
    .join(" ") || "My Theme";
}

function guessAuthor(env = process.env) {
  return env.CLAWD_THEME_AUTHOR
    || env.GIT_AUTHOR_NAME
    || env.GIT_COMMITTER_NAME
    || env.USERNAME
    || env.USER
    || "Your Name";
}

function getDefaultThemesRoot(platform = process.platform, env = process.env, homeDir = os.homedir()) {
  const pathApi = platform === "win32" ? path.win32 : path.posix;
  if (platform === "win32") {
    const appData = env.APPDATA || pathApi.join(homeDir, "AppData", "Roaming");
    return pathApi.join(appData, "clawd-on-desk", "themes");
  }
  if (platform === "darwin") {
    return pathApi.join(homeDir, "Library", "Application Support", "clawd-on-desk", "themes");
  }
  const configHome = env.XDG_CONFIG_HOME || pathApi.join(homeDir, ".config");
  return pathApi.join(configHome, "clawd-on-desk", "themes");
}

function parseArgs(argv) {
  const opts = {
    themeId: "",
    name: "",
    author: "",
    targetDir: "",
    help: false,
  };
  const readValue = (flag, index) => {
    const value = argv[index + 1];
    if (!value || value.startsWith("--")) {
      throw new Error(`Missing value for ${flag}`);
    }
    return value;
  };
  for (let i = 0; i < argv.length; i += 1) {
    const arg = argv[i];
    if (arg === "--help" || arg === "-h") {
      opts.help = true;
      continue;
    }
    if (arg === "--name") {
      opts.name = readValue(arg, i);
      i += 1;
      continue;
    }
    if (arg === "--author") {
      opts.author = readValue(arg, i);
      i += 1;
      continue;
    }
    if (arg === "--target") {
      opts.targetDir = readValue(arg, i);
      i += 1;
      continue;
    }
    if (arg.startsWith("--")) {
      throw new Error(`Unknown option: ${arg}`);
    }
    if (!opts.themeId) {
      opts.themeId = arg;
      continue;
    }
    throw new Error(`Unexpected extra argument: ${arg}`);
  }
  return opts;
}

function resolveTarget(options = {}) {
  const requestedId = slugifyThemeId(options.themeId || "my-theme");
  if (options.targetDir) {
    const targetDir = path.resolve(options.targetDir);
    return {
      themesRoot: path.dirname(targetDir),
      themeId: path.basename(targetDir),
      targetDir,
      autoGeneratedId: false,
    };
  }
  const themesRoot = path.resolve(options.themesRoot || getDefaultThemesRoot(options.platform, options.env, options.homeDir));
  if (options.themeId) {
    return {
      themesRoot,
      themeId: requestedId,
      targetDir: path.join(themesRoot, requestedId),
      autoGeneratedId: false,
    };
  }
  let themeId = requestedId;
  let targetDir = path.join(themesRoot, themeId);
  let suffix = 2;
  while (fs.existsSync(targetDir)) {
    themeId = `my-theme-${suffix}`;
    targetDir = path.join(themesRoot, themeId);
    suffix += 1;
  }
  return {
    themesRoot,
    themeId,
    targetDir,
    autoGeneratedId: true,
  };
}

function copyTemplateDir(sourceDir, targetDir) {
  fs.cpSync(sourceDir, targetDir, { recursive: true });
}

function patchThemeJsonTemplate(sourceText, replacements) {
  return sourceText
    .replace(/"name":\s*"[^"]*"/, `"name": ${JSON.stringify(replacements.name)}`)
    .replace(/"author":\s*"[^"]*"/, `"author": ${JSON.stringify(replacements.author)}`)
    .replace(/\r?\n[ \t]*"_scaffoldOnly":\s*true,?/, "");
}

function createThemeScaffold(options = {}) {
  if (!fs.existsSync(TEMPLATE_DIR)) {
    throw new Error(`Template directory not found: ${TEMPLATE_DIR}`);
  }
  const resolved = resolveTarget(options);
  if (fs.existsSync(resolved.targetDir)) {
    throw new Error(`Target theme directory already exists: ${resolved.targetDir}`);
  }
  fs.mkdirSync(resolved.themesRoot, { recursive: true });
  copyTemplateDir(TEMPLATE_DIR, resolved.targetDir);

  const displayName = (options.name && options.name.trim()) || humanizeThemeId(resolved.themeId);
  const author = (options.author && options.author.trim()) || guessAuthor(options.env);
  const themeJsonPath = path.join(resolved.targetDir, "theme.json");
  const patched = patchThemeJsonTemplate(fs.readFileSync(themeJsonPath, "utf8"), {
    name: displayName,
    author,
  });
  fs.writeFileSync(themeJsonPath, patched, "utf8");

  return {
    themeId: resolved.themeId,
    name: displayName,
    author,
    targetDir: resolved.targetDir,
    themesRoot: resolved.themesRoot,
    autoGeneratedId: resolved.autoGeneratedId,
  };
}

function formatHelp() {
  return [
    "Usage:",
    "  node scripts/create-theme.js [theme-id] [--name \"Display Name\"] [--author \"Your Name\"] [--target /absolute/path/to/theme]",
    "",
    "Examples:",
    "  node scripts/create-theme.js",
    "  node scripts/create-theme.js pixel-cat --name \"Pixel Cat\" --author \"Ruller\"",
    "  npm run create-theme -- pixel-cat",
  ].join("\n");
}

function formatSuccess(result) {
  return [
    `Created theme scaffold: ${result.targetDir}`,
    "",
    "Next steps:",
    "  1. Edit theme.json metadata and file mappings",
    "  2. Replace assets/idle-follow.svg and add your own assets/",
    `  3. Validate with: node scripts/validate-theme.js ${result.targetDir}`,
    "  4. Restart Clawd and select the theme from Settings -> Theme",
  ].join("\n");
}

function main(argv = process.argv.slice(2)) {
  const opts = parseArgs(argv);
  if (opts.help) {
    console.log(formatHelp());
    return 0;
  }
  const result = createThemeScaffold(opts);
  console.log(formatSuccess(result));
  return 0;
}

if (require.main === module) {
  try {
    process.exitCode = main();
  } catch (err) {
    console.error(err && err.message ? err.message : String(err));
    console.error("");
    console.error(formatHelp());
    process.exitCode = 1;
  }
}

module.exports = {
  createThemeScaffold,
  formatHelp,
  getDefaultThemesRoot,
  guessAuthor,
  humanizeThemeId,
  parseArgs,
  resolveTarget,
  slugifyThemeId,
};
