// src/actions/dead/detectActiveCodeWorkspace.ts
import fs2 from "node:fs";
import os from "node:os";
import path2 from "node:path";

// src/actions/dead/parseCodeWorkspace.ts
import fs from "node:fs";
import path from "node:path";
function consumeString(input, ctx, quote) {
  ctx.out += input[ctx.i];
  ctx.i += 1;
  while (ctx.i < input.length) {
    const ch = input[ctx.i];
    ctx.out += ch;
    if (ch === "\\" && ctx.i + 1 < input.length) {
      ctx.out += input[ctx.i + 1];
      ctx.i += 2;
      continue;
    }
    if (ch === quote) {
      ctx.i += 1;
      return;
    }
    ctx.i += 1;
  }
}
function consumeLineComment(input, ctx) {
  while (ctx.i < input.length && input[ctx.i] !== "\n") ctx.i += 1;
}
function consumeBlockComment(input, ctx) {
  ctx.i += 2;
  while (ctx.i < input.length && !(input[ctx.i] === "*" && input[ctx.i + 1] === "/")) ctx.i += 1;
  ctx.i += 2;
}
function stripJsonc(input) {
  const ctx = { i: 0, out: "" };
  while (ctx.i < input.length) {
    const ch = input[ctx.i];
    if (ch === '"' || ch === "'") {
      consumeString(input, ctx, ch);
      continue;
    }
    const next = ctx.i + 1 < input.length ? input[ctx.i + 1] : "";
    if (ch === "/" && next === "/") {
      consumeLineComment(input, ctx);
      continue;
    }
    if (ch === "/" && next === "*") {
      consumeBlockComment(input, ctx);
      continue;
    }
    ctx.out += ch;
    ctx.i += 1;
  }
  return ctx.out.replaceAll(/,(\s*[}\]])/g, "$1");
}
function parseWorkspaceJson(workspaceFilePath, stripped) {
  try {
    return JSON.parse(stripped);
  } catch (ex) {
    throw new Error(
      `Failed to parse code-workspace file ${workspaceFilePath}: ${ex instanceof Error ? ex.message : String(ex)}`,
      { cause: ex }
    );
  }
}
function parseCodeWorkspace(workspaceFilePath) {
  const raw = fs.readFileSync(workspaceFilePath, "utf8");
  const stripped = stripJsonc(raw);
  const parsed = parseWorkspaceJson(workspaceFilePath, stripped);
  if (!parsed.folders || !Array.isArray(parsed.folders)) return [];
  const baseDir = path.dirname(workspaceFilePath);
  const results = [];
  for (const entry of parsed.folders) {
    if (typeof entry.path !== "string") continue;
    const rawPath = entry.path;
    const absolutePath = path.isAbsolute(rawPath) ? rawPath : path.resolve(baseDir, rawPath);
    results.push({
      absolutePath,
      name: typeof entry.name === "string" ? entry.name : void 0,
      rawPath
    });
  }
  return results;
}

// src/actions/dead/detectActiveCodeWorkspace.ts
function uriToPath(uri) {
  if (!uri.startsWith("file://")) return void 0;
  try {
    const parsed = new URL(uri);
    let pathname = decodeURIComponent(parsed.pathname);
    if (process.platform === "win32" && pathname.startsWith("/") && /^\/[A-Za-z]:/.test(pathname)) {
      pathname = pathname.slice(1);
    }
    return pathname;
  } catch {
    return void 0;
  }
}
function isPathContainedIn(container, target) {
  const resolvedContainer = path2.resolve(container);
  const resolvedTarget = path2.resolve(target);
  return resolvedTarget === resolvedContainer || resolvedTarget.startsWith(`${resolvedContainer}${path2.sep}`);
}
function hasWorkspaceFileContainingPath(workspaceFilePath, targetPath) {
  try {
    const folders = parseCodeWorkspace(workspaceFilePath);
    return folders.some((folder) => isPathContainedIn(folder.absolutePath, targetPath));
  } catch {
    return false;
  }
}
function getEditorStorageRoots() {
  const home = os.homedir();
  return [
    path2.join(home, "Library", "Application Support", "Code", "User", "workspaceStorage"),
    path2.join(home, "Library", "Application Support", "Cursor", "User", "workspaceStorage"),
    path2.join(home, ".config", "Code", "User", "workspaceStorage"),
    path2.join(home, ".config", "Cursor", "User", "workspaceStorage")
  ].filter((root) => fs2.existsSync(root));
}
function readWorkspaceCandidate(workspaceJsonPath, resolvedStart) {
  let parsed;
  try {
    parsed = JSON.parse(fs2.readFileSync(workspaceJsonPath, "utf8"));
  } catch {
    return void 0;
  }
  if (typeof parsed.workspace !== "string") return void 0;
  const candidate = uriToPath(parsed.workspace);
  if (!(candidate != null && candidate.length > 0)) return void 0;
  if (!candidate.endsWith(".code-workspace")) return void 0;
  if (!fs2.existsSync(candidate)) return void 0;
  if (!hasWorkspaceFileContainingPath(candidate, resolvedStart)) return void 0;
  return candidate;
}
function updateBestFromEntry(storageRoot, entry, resolvedStart, best) {
  const workspaceJsonPath = path2.join(storageRoot, entry, "workspace.json");
  let stat;
  try {
    stat = fs2.statSync(workspaceJsonPath);
  } catch {
    return best;
  }
  const candidate = readWorkspaceCandidate(workspaceJsonPath, resolvedStart);
  if (!(candidate != null && candidate.length > 0)) return best;
  if (!best || stat.mtimeMs > best.mtimeMs) {
    return { mtimeMs: stat.mtimeMs, path: candidate };
  }
  return best;
}
function scanStorageRoot(storageRoot, resolvedStart, best) {
  let entries;
  try {
    entries = fs2.readdirSync(storageRoot);
  } catch {
    return best;
  }
  let nextBest = best;
  for (const entry of entries) {
    nextBest = updateBestFromEntry(storageRoot, entry, resolvedStart, nextBest);
  }
  return nextBest;
}
function detectActiveCodeWorkspace(startDir) {
  const resolvedStart = path2.resolve(startDir);
  let best;
  for (const storageRoot of getEditorStorageRoots()) {
    best = scanStorageRoot(storageRoot, resolvedStart, best);
  }
  return best?.path;
}
export {
  detectActiveCodeWorkspace,
  hasWorkspaceFileContainingPath
};
//# sourceMappingURL=detectActiveCodeWorkspace.mjs.map
