const WEIGHT_RANK = { light: 0, medium: 1, heavy: 2 };

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

function splitSubtasks(text) {
  const trimmed = text.trim();
  const lines = trimmed.split(/\n/).map((l) => l.replace(/^[\s\-*•\d.)]+\s*/, "").trim()).filter(Boolean);
  if (lines.length >= 2) return lines;
  const parts = trimmed.split(/\s*,\s*|\s+ve\s+|\s+and\s+/i).filter((p) => p.trim().length > 3);
  if (parts.length >= 2) return parts;
  return [trimmed];
}

function matchKeywords(text, keywords) {
  const n = normalize(text);
  return keywords.some((kw) => n.includes(normalize(kw)));
}

function parseEstimatedFiles(text) {
  const patterns = [
    /(\d+)\s*\+\s*(?:file|files|dosya)/i,
    /(?:file|files|dosya)\s*[:=]?\s*(\d+)/i,
    /(\d+)\s*(?:file|files|dosya)/i
  ];
  for (const re of patterns) {
    const m = text.match(re);
    if (m?.[1]) return Number(m[1]);
  }
  return null;
}

function findBestTaskType(text, matrix) {
  let bestType = null;
  for (const tt of matrix.task_types || []) {
    if (matchKeywords(text, tt.keywords || [])) {
      if (!bestType || WEIGHT_RANK[tt.weight_default || "light"] > WEIGHT_RANK[bestType.weight_default || "light"]) {
        bestType = tt;
      }
    }
  }
  return bestType;
}

function classifySubtask(text, matrix) {
  const c = matrix.classification;
  const reasons = [];
  const estimatedFiles = parseEstimatedFiles(text);

  if (matchKeywords(text, c.heavy_keywords || [])) {
    reasons.push("heavy keyword");
    return { weight: "heavy", reasons, taskType: findBestTaskType(text, matrix), signals: { estimated_files: estimatedFiles } };
  }

  if (matchKeywords(text, c.security_keywords || [])) {
    reasons.push("security domain");
    const securityFloor = c.security_override_min || "medium";
    return {
      weight: securityFloor,
      reasons,
      taskType: findBestTaskType(text, matrix),
      signals: { estimated_files: estimatedFiles }
    };
  }

  if (matchKeywords(text, c.medium_keywords || [])) {
    reasons.push("medium keyword");
    return {
      weight: "medium",
      reasons,
      taskType: findBestTaskType(text, matrix),
      signals: { estimated_files: estimatedFiles }
    };
  }

  const bestType = findBestTaskType(text, matrix);
  if (bestType) {
    reasons.push(`task_type:${bestType.id}`);
    return {
      weight: bestType.weight_default || "medium",
      reasons,
      taskType: bestType,
      signals: { estimated_files: estimatedFiles }
    };
  }

  reasons.push("ambiguous default");
  return { weight: c.ambiguous_default || "medium", reasons, signals: { estimated_files: estimatedFiles } };
}

function parseIntent(text, matrix) {
  const subtasks = splitSubtasks(text);
  const useMultiple = subtasks.length >= 2;
  const segments = (useMultiple ? subtasks : [text.trim()]).map((sub, index) => ({
    index: index + 1,
    text: sub,
    classification: classifySubtask(sub, matrix)
  }));

  return {
    rawText: text,
    useMultiple,
    subtasks,
    overrides: {
      workflow: /\/workflow\b/i.test(text),
      skill: /\/skill\b/i.test(text)
    },
    segments
  };
}

module.exports = {
  parseIntent,
  matchKeywords
};
