import { existsSync } from "node:fs";
import path from "node:path";
import type { SystemSummary } from "@qjclaw/shared-types";

function uniquePaths(paths: Array<string | undefined>): string[] {
  return [...new Set(paths.map((value) => value?.trim()).filter((value): value is string => Boolean(value)))];
}

export function resolveGenericSkillsRoot(systemSummary: SystemSummary): string {
  const envRoot = process.env.QJCLAW_SKILL_CATALOG_ROOT?.trim();
  const devRepoSkillsRoot = path.resolve(systemSummary.appPath, "..", "..", "skills");
  const legacyRepoSkillsRoot = path.resolve(systemSummary.appPath, "..", "..", "q-skills", "skills");
  const cwdSkillsRoot = path.resolve(process.cwd(), "skills");
  const packagedSkillsRoot = systemSummary.isPackaged
    ? path.join(systemSummary.resourcesPath, "skills")
    : undefined;

  const candidates = uniquePaths([
    envRoot,
    packagedSkillsRoot,
    devRepoSkillsRoot,
    cwdSkillsRoot,
    legacyRepoSkillsRoot
  ]);

  return candidates.find((candidate) => existsSync(candidate)) ?? candidates[0] ?? devRepoSkillsRoot;
}
