// Chunk markdown files by ## headers with file:line references
// Constraint: Max 500 tokens per chunk (spec.md:66)

export interface MarkdownChunk {
  file: string;
  line: number;
  content: string;
  heading: string;
}

/**
 * Split markdown content by ## headers, preserving file:line references
 * @param filePath - Absolute path to markdown file
 * @param content - Full markdown content
 * @returns Array of chunks with metadata
 */
export function chunkMarkdown(
  filePath: string,
  content: string,
): MarkdownChunk[] {
  const lines = content.split("\n");
  const chunks: MarkdownChunk[] = [];
  let currentChunk: string[] = [];
  let currentHeading = "Introduction";
  let chunkStartLine = 1;

  for (let i = 0; i < lines.length; i++) {
    const line = lines[i];
    const lineNumber = i + 1;

    // Detect ## headers (level 2)
    if (line.startsWith("## ")) {
      // Save previous chunk if exists
      if (currentChunk.length > 0) {
        chunks.push({
          file: filePath,
          line: chunkStartLine,
          content: currentChunk.join("\n").trim(),
          heading: currentHeading,
        });
      }

      // Start new chunk
      currentHeading = line.replace(/^##\s+/, "").trim();
      currentChunk = [line];
      chunkStartLine = lineNumber;
    } else {
      currentChunk.push(line);
    }
  }

  // Save final chunk
  if (currentChunk.length > 0) {
    chunks.push({
      file: filePath,
      line: chunkStartLine,
      content: currentChunk.join("\n").trim(),
      heading: currentHeading,
    });
  }

  return chunks;
}
