/**
 * Dzielenie dokumentu OWU na fragmenty wg numeracji paragrafów -- port
 * logiki z lokalnego MVP (src/chunking.py). Zasada bez zmian: dzielimy po
 * "§ N" / "Art. N", nie po stałej liczbie znaków, żeby cytowanie
 * paragrafu w odpowiedzi AI było precyzyjne.
 */

export interface RawChunk {
  paragraphLabel: string;
  chunkIndex: number;
  text: string;
}

const PARAGRAPH_HEADER_RE = /(§\s*\d+[a-zA-Z]?(?:\s+ust\.\s*\d+)?|Art\.\s*\d+[a-zA-Z]?)/g;

const MAX_CHARS = 1200;

export function chunkDocument(rawText: string): RawChunk[] {
  const text = rawText.replace(/\r\n/g, "\n").trim();
  const matches = [...text.matchAll(PARAGRAPH_HEADER_RE)];

  const chunks: RawChunk[] = [];

  if (matches.length === 0) {
    // Brak rozpoznawalnej numeracji paragrafów -- dzielimy po prostu na
    // bloki o stałej długości, żeby dokument i tak dało się przeszukać.
    for (let i = 0; i < text.length; i += MAX_CHARS) {
      chunks.push({
        paragraphLabel: `fragment ${chunks.length + 1}`,
        chunkIndex: chunks.length,
        text: text.slice(i, i + MAX_CHARS).trim(),
      });
    }
    return chunks;
  }

  for (let i = 0; i < matches.length; i++) {
    const start = matches[i].index!;
    const end = i + 1 < matches.length ? matches[i + 1].index! : text.length;
    const label = matches[i][0].replace(/\s+/g, " ").trim();
    const body = text.slice(start, end).trim();

    if (body.length <= MAX_CHARS) {
      chunks.push({ paragraphLabel: label, chunkIndex: chunks.length, text: body });
    } else {
      // Bardzo długi paragraf -- dzielimy dalej, ale zachowujemy tę samą
      // etykietę paragrafu we wszystkich częściach (cytowanie zostaje trafne).
      for (let j = 0; j < body.length; j += MAX_CHARS) {
        chunks.push({
          paragraphLabel: label,
          chunkIndex: chunks.length,
          text: body.slice(j, j + MAX_CHARS).trim(),
        });
      }
    }
  }

  return chunks;
}
