"""Content filtering utilities for document retrieval."""

import re


def filter_document_content(content: str, filter_spec: dict) -> str:
    """Filter document content based on line ranges and/or grep patterns.

    Args:
        content: The document content to filter
        filter_spec: Dictionary with optional keys:
            - start_line: Start line (0-indexed, inclusive)
            - end_line: End line (exclusive, like Python slice)
            - grep_pattern: Regex pattern to search (case-insensitive)
            - context_lines: Lines to show before/after grep matches (default 0)

    Returns:
        Filtered content string
    """
    if not content:
        return content

    lines = content.split("\n")

    # Apply line range filtering
    start_line = filter_spec.get("start_line")
    end_line = filter_spec.get("end_line")

    if start_line is not None or end_line is not None:
        start = start_line if start_line is not None else 0
        end = end_line if end_line is not None else len(lines)
        lines = lines[start:end]

    # Apply grep pattern filtering
    grep_pattern = filter_spec.get("grep_pattern")
    if grep_pattern:
        context_lines = filter_spec.get("context_lines", 0)
        matching_indices = set()

        try:
            pattern = re.compile(grep_pattern, re.IGNORECASE)
        except re.error as e:
            # If regex is invalid, return error message
            return f"Error: Invalid regex pattern: {e}"

        # Find all matching lines
        for i, line in enumerate(lines):
            if pattern.search(line):
                # Add the matching line and context
                for j in range(
                    max(0, i - context_lines), min(len(lines), i + context_lines + 1)
                ):
                    matching_indices.add(j)

        if not matching_indices:
            return f"No matches found for pattern: {grep_pattern}"

        # Build output with line numbers and context separators
        filtered_lines = []
        sorted_indices = sorted(matching_indices)

        for idx, line_num in enumerate(sorted_indices):
            # Add separator if there's a gap from previous line
            if idx > 0 and line_num > sorted_indices[idx - 1] + 1:
                filtered_lines.append("--")
            filtered_lines.append(lines[line_num])

        lines = filtered_lines

    return "\n".join(lines)
