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

function codexHomeForTarget(target) {
  return path.basename(target.dir) === "skills" ? path.dirname(target.dir) : target.dir;
}

function openCodeProjectRootForTarget(target) {
  const parent = path.dirname(target.dir);
  return path.basename(parent) === ".opencode" ? path.dirname(parent) : process.cwd();
}

function openCodeConfigPathsForTarget(target) {
  if (target.scope === "user") {
    const parent = path.dirname(target.dir);
    const root = ["skill", "skills"].includes(path.basename(target.dir)) ? parent : target.dir;
    return [path.join(root, "opencode.json"), path.join(root, "opencode.jsonc")];
  }
  const projectRoot = openCodeProjectRootForTarget(target);
  return [
    path.join(projectRoot, "opencode.json"),
    path.join(projectRoot, "opencode.jsonc"),
    path.join(projectRoot, ".opencode", "opencode.json"),
    path.join(projectRoot, ".opencode", "opencode.jsonc"),
  ];
}

function registryPathForScope(options = {}) {
  if (options.scope === "project") {
    return path.join(options.cwd || process.cwd(), ".oh-skillhub", "registry.json");
  }
  return path.join(options.homeDir || os.homedir(), ".oh-skillhub", "registry.json");
}

function defaultPayloadRoot(target, pluginName) {
  return path.join(target.dir, ".oh-skillhub", "plugins", pluginName, target.agent);
}

// Collect OpenCode plugin entries from both the current `plugins` (plural) field
// and the deprecated `plugin` (singular) field. OpenCode V2 reads `plugins`;
// the singular form is deprecated but still present in older configs.
function collectOpenCodePluginEntries(parsed) {
  if (!parsed) return [];
  const entries = [];
  if (Array.isArray(parsed.plugins)) entries.push(...parsed.plugins);
  if (Array.isArray(parsed.plugin)) entries.push(...parsed.plugin);
  return entries;
}

module.exports = {
  codexHomeForTarget,
  openCodeConfigPathsForTarget,
  openCodeProjectRootForTarget,
  registryPathForScope,
  defaultPayloadRoot,
  collectOpenCodePluginEntries,
};