import path2 from 'node:path';

// src/platform/prompts/rule-selector.ts
function isPromptMarkdownFileReference(asset) {
  return typeof asset !== "string";
}
function isPromptRuleGroupAsset(asset) {
  return typeof asset !== "string" && !("kind" in asset && asset.kind === "file-reference");
}
function getPromptMarkdownAssetDedupKey(asset) {
  return isPromptMarkdownFileReference(asset) ? `file:${path2.normalize(asset.filePath)}` : `inline:${asset.trim()}`;
}

// src/platform/prompts/rule-selector.ts
function normalizePromptFilePath(filePath) {
  return path2.normalize(filePath).replace(/\\/g, "/").trim();
}
function getNormalizedFileNamePatterns(group) {
  return (group.fileNamePatterns || []).map((pattern) => pattern.trim()).filter(Boolean);
}
function getNormalizedRules(group) {
  return (group.rules || []).filter((asset) => typeof asset === "string" ? Boolean(asset.trim()) : Boolean(asset.filePath.trim()));
}
function createFileMatchCandidates(filePath) {
  const normalized = normalizePromptFilePath(filePath);
  if (!normalized) {
    return [];
  }
  const baseName = path2.posix.basename(normalized);
  return normalized === baseName ? [normalized] : [normalized, baseName];
}
function compileFileNamePattern(pattern) {
  try {
    return new RegExp(pattern);
  } catch (error) {
    throw new Error(
      `\uC720\uD6A8\uD558\uC9C0 \uC54A\uC740 fileNamePatterns \uC815\uADDC\uC2DD\uC785\uB2C8\uB2E4: ${pattern}
${error instanceof Error ? error.message : String(error)}`
    );
  }
}
function normalizePromptTargetFilePaths(filePaths) {
  return filePaths.map(normalizePromptFilePath).filter(Boolean);
}
function matchesPromptRuleGroup(group, targetFilePaths) {
  const normalizedPatterns = getNormalizedFileNamePatterns(group);
  if (normalizedPatterns.length === 0) {
    return true;
  }
  if (targetFilePaths.length === 0) {
    return false;
  }
  return normalizedPatterns.some((pattern) => {
    const regex = compileFileNamePattern(pattern);
    return targetFilePaths.some(
      (filePath) => createFileMatchCandidates(filePath).some((candidate) => regex.test(candidate))
    );
  });
}
function resolvePromptRules(ruleAssets, targetFilePaths = []) {
  if (!ruleAssets || ruleAssets.length === 0) {
    return void 0;
  }
  const normalizedTargetFilePaths = normalizePromptTargetFilePaths(targetFilePaths);
  const resolvedRules = [];
  const seenRules = /* @__PURE__ */ new Set();
  for (const asset of ruleAssets) {
    const nextRules = !isPromptRuleGroupAsset(asset) ? [asset] : matchesPromptRuleGroup(asset, normalizedTargetFilePaths) ? getNormalizedRules(asset) : [];
    for (const rule of nextRules) {
      const dedupeKey = getPromptMarkdownAssetDedupKey(rule);
      if (seenRules.has(dedupeKey)) {
        continue;
      }
      seenRules.add(dedupeKey);
      resolvedRules.push(rule);
    }
  }
  return resolvedRules.length > 0 ? resolvedRules : void 0;
}

export { normalizePromptTargetFilePaths, resolvePromptRules };
