function normalize(text) {
  return text.toLowerCase().normalize("NFD").replace(/\p{M}/gu, "");
}

const OVERRIDE_PHRASES = [
  "cross-repo override",
  "capint:cross-repo",
  "capint cross repo",
  "başka repo override",
  "workspace override"
];

const SIBLING_REPO_NAMES = ["prismx", "prismx-cli", "efesusstone"];

const PATH_PATTERNS = [
  /\.\.[\\/][^\s,;'"`]*/g,
  /(?:^|[\s'"`])([a-z]:[\\/][^\s'"`,]+)/gi,
  /(?:^|[\s'"`])\/(?:home|Users|var)\/[^\s'"`,]+/gi,
  new RegExp(
    `(?:^|[\\s'"\\\`])((?:${SIBLING_REPO_NAMES.join("|")})[\\\\/][^\\s'"\\\`,]+)`,
    "gi"
  )
];

function extractSuspiciousPaths(text) {
  const found = [];
  for (const re of PATH_PATTERNS) {
    for (const m of text.matchAll(re)) {
      const p = (m[1] || m[0]).trim().replace(/^[\s'"`]+|[\s'"`,]+$/g, "");
      if (p && !found.includes(p)) found.push(p);
    }
  }
  return found;
}

function hasCrossRepoOverride(text) {
  const n = normalize(text);
  return OVERRIDE_PHRASES.some((p) => n.includes(normalize(p)));
}

function detectWorkspaceBoundary(text) {
  const suspicious_paths = extractSuspiciousPaths(text);
  const has_override = hasCrossRepoOverride(text);
  const violated = suspicious_paths.length > 0 && !has_override;
  return {
    violated,
    has_override,
    suspicious_paths,
    override_hint: violated
      ? 'Add explicit phrase "cross-repo override" to edit files outside this workspace'
      : null
  };
}

module.exports = {
  detectWorkspaceBoundary,
  extractSuspiciousPaths,
  hasCrossRepoOverride,
  OVERRIDE_PHRASES
};
