import re
from typing import List, Tuple, Union, Any
from .base import BaseChunker, Chunk


class WordChunker(BaseChunker):
    def __init__(
        self,
        tokenizer: Union[str, Any] = "gpt2",
        chunk_size: int = 512,
        chunk_overlap: int = 128,
    ):
        """Initialize the WordChunker with configuration parameters.

        Args:
            tokenizer: The tokenizer instance to use for encoding/decoding
            chunk_size: Maximum number of tokens per chunk
            chunk_overlap: Maximum number of tokens to overlap between chunks
            mode: Tokenization mode - "heuristic" (space-based) or "advanced" (handles punctuation)

        Raises:
            ValueError: If chunk_size <= 0 or chunk_overlap >= chunk_size or invalid mode
        """
        super().__init__(tokenizer)

        if chunk_size <= 0:
            raise ValueError("chunk_size must be positive")
        if chunk_overlap >= chunk_size:
            raise ValueError("chunk_overlap must be less than chunk_size")

        self.chunk_size = chunk_size
        self.chunk_overlap = chunk_overlap

    def _split_into_words(self, text: str) -> List[str]:
        """Split text into words based on the selected mode.

        Args:
            text: Input text to be split into words

        Returns:
            List of words
        """
        return re.findall(r"\S+", text)

    def _create_chunk(
        self, words: List[str], text:str, token_count: int
    ) -> Tuple[Chunk, int]:
        """Create a chunk from a list of words.

        Args:
            words: List of words to create chunk from
            start_idx: Starting index in original text
            end_idx: Ending index in original text

        Returns:
            Tuple of (Chunk object, number of tokens in chunk)
        """
        chunk_text = " ".join(words)
        start_index = text.find(chunk_text)
        return Chunk(
            text=chunk_text,
            start_index=start_index,
            end_index=start_index + len(chunk_text),
            token_count=token_count
        )

    def _get_word_list_token_counts(self, words: List[str]) -> List[int]:
        """Get the number of tokens for each word in a list.

        Args:
            words: List of words

        Returns:
            List of token counts for each word
        """
        words = [
            " " + word.strip() for word in words
        ]  # Add space in the beginning because tokenizers usually split that differently
        encodings = self._encode_batch(words)
        return [len(encoding) for encoding in encodings]

    def chunk(self, text: str) -> List[Chunk]:
        """Split text into overlapping chunks based on words while respecting token limits.

        Args:
            text: Input text to be chunked

        Returns:
            List of Chunk objects containing the chunked text and metadata
        """
        if not text.strip():
            return []

        words = self._split_into_words(text)
        lengths = self._get_word_list_token_counts(words)
        chunks = []

        # Saving the current chunk
        current_chunk = []
        current_chunk_length = 0

        for i, (word, length) in enumerate(zip(words, lengths)):
            if current_chunk_length + length <= self.chunk_size:
                current_chunk.append(word)
                current_chunk_length += length
            else:
                chunk = self._create_chunk(current_chunk, text, current_chunk_length)
                chunks.append(chunk)

                # update the current_chunk and previous chunk
                previous_chunk_length = current_chunk_length

                current_chunk = []
                current_chunk_length = 0

                overlap = []
                overlap_length = 0
                # calculate the overlap from the current chunk in reverse
                for j in range(0, previous_chunk_length):
                    cwi = i - 1 - j
                    oword = words[cwi]
                    olength = lengths[cwi]
                    if overlap_length + olength <= self.chunk_overlap:
                        overlap.append(oword)
                        overlap_length += olength
                    else:
                        break

                current_chunk = [w for w in reversed(overlap)]
                current_chunk_length = overlap_length

                current_chunk.append(word)
                current_chunk_length += length

        # Add the final chunk if it has any words
        if current_chunk:
            chunk = self._create_chunk(
                current_chunk, text, current_chunk_length
            )
            chunks.append(chunk)
        return chunks

    def __repr__(self) -> str:
        return (
            f"WordChunker(chunk_size={self.chunk_size}, "
            f"chunk_overlap={self.chunk_overlap})"
        )
