from __future__ import annotations

from dataclasses import dataclass


@dataclass(frozen=True)
class ChunkSpan:
    start_line: int
    end_line: int
    text: str


def chunk_text(text: str, max_lines: int, overlap: int) -> list[ChunkSpan]:
    if max_lines <= 0:
        raise ValueError("max_lines must be > 0")
    if overlap < 0:
        raise ValueError("overlap must be >= 0")
    if overlap >= max_lines:
        raise ValueError("overlap must be smaller than max_lines")

    lines = text.splitlines()
    if not lines:
        return []

    step = max_lines - overlap
    chunks: list[ChunkSpan] = []
    start = 0

    while start < len(lines):
        end = min(start + max_lines, len(lines))
        chunk_lines = lines[start:end]
        chunk_text_value = "\n".join(chunk_lines)
        chunks.append(
            ChunkSpan(
                start_line=start + 1,
                end_line=end,
                text=chunk_text_value,
            )
        )
        if end == len(lines):
            break
        start += step

    return chunks
