from __future__ import annotations

import re
from dataclasses import dataclass, field
from pathlib import Path, PurePosixPath
from typing import TYPE_CHECKING, Pattern

if TYPE_CHECKING:
    from ..config import Config


DEFAULT_MAX_FILE_BYTES = 2 * 1024 * 1024
DEFAULT_MAX_TOTAL_BYTES = 32 * 1024 * 1024
_UTF8_SIZE_CHARS = 64 * 1024


class DocumentContentError(ValueError):
    """Raised when a stored-document-content policy is invalid."""


class DocumentContentLimitError(DocumentContentError):
    """Raised when selected document content exceeds the configured limit."""


def utf8_size(value: str) -> int:
    """Compute UTF-8 size without allocating a second full document buffer."""
    return sum(
        len(value[offset:offset + _UTF8_SIZE_CHARS].encode("utf-8"))
        for offset in range(0, len(value), _UTF8_SIZE_CHARS)
    )


def _relative_posix(value: str, field_name: str) -> str:
    if not isinstance(value, str):
        raise DocumentContentError(f"{field_name} must be a string")
    if not value:
        raise DocumentContentError(f"{field_name} must not be empty")
    if "\\" in value:
        raise DocumentContentError(
            f"{field_name} must use project-relative POSIX '/' separators"
        )
    if value.startswith("/") or re.match(r"^[A-Za-z]:", value):
        raise DocumentContentError(f"{field_name} must be project-relative")

    parts = PurePosixPath(value).parts
    if any(part == ".." for part in parts):
        raise DocumentContentError(f"{field_name} must not contain '..'")
    if parts and parts[0] == "/":
        raise DocumentContentError(f"{field_name} must be project-relative")

    # A leading './' has no semantic value and would otherwise make matching
    # surprisingly dependent on how a caller spelled the same relative path.
    while value.startswith("./"):
        value = value[2:]
    if not value or value == ".":
        raise DocumentContentError(f"{field_name} must name a file or glob")
    return value


def _segment_regex(segment: str) -> str:
    """Translate one path segment using shell-style glob semantics."""
    result: list[str] = []
    index = 0
    while index < len(segment):
        char = segment[index]
        if char == "*":
            result.append("[^/]*")
        elif char == "?":
            result.append("[^/]")
        elif char == "[":
            end = index + 1
            if end < len(segment) and segment[end] in ("!", "^"):
                end += 1
            if end < len(segment) and segment[end] == "]":
                end += 1
            while end < len(segment) and segment[end] != "]":
                end += 1
            if end >= len(segment):
                result.append(r"\[")
            else:
                stuff = segment[index + 1:end]
                if stuff.startswith("!"):
                    stuff = "^" + stuff[1:]
                elif stuff.startswith("^"):
                    stuff = "\\" + stuff
                stuff = stuff.replace("\\", r"\\")
                result.append(f"[{stuff}]")
                index = end
        else:
            result.append(re.escape(char))
        index += 1
    return "".join(result)


def _compile_glob(pattern: str) -> Pattern[str]:
    segments = pattern.split("/")
    expression: list[str] = ["^"]
    for index, segment in enumerate(segments):
        is_last = index == len(segments) - 1
        if segment == "**":
            if is_last:
                expression.append(".*")
            else:
                expression.append("(?:[^/]+/)*")
            continue

        expression.append(_segment_regex(segment))
        if not is_last:
            expression.append("/")
    expression.append("$")
    try:
        return re.compile("".join(expression))
    except re.error as exc:
        raise DocumentContentError(f"invalid document content glob {pattern!r}: {exc}") from exc


@dataclass
class DocumentContentPolicy:
    """Selection and per-file safety limits for persisted document snapshots.

    The aggregate ``max_total_bytes`` value is intentionally declarative. A
    builder or updater owns the aggregate transaction and therefore enforces
    that limit across all parsed documents.
    """

    include: tuple[str, ...] = ()
    exclude: tuple[str, ...] = ()
    max_file_bytes: int = DEFAULT_MAX_FILE_BYTES
    max_total_bytes: int = DEFAULT_MAX_TOTAL_BYTES
    on_limit: str = "error"
    _include_regex: tuple[Pattern[str], ...] = field(
        init=False, repr=False, compare=False
    )
    _exclude_regex: tuple[Pattern[str], ...] = field(
        init=False, repr=False, compare=False
    )

    def __post_init__(self) -> None:
        include = tuple(
            _relative_posix(value, f"include[{index}]")
            for index, value in enumerate(self.include)
        )
        exclude = tuple(
            _relative_posix(value, f"exclude[{index}]")
            for index, value in enumerate(self.exclude)
        )
        if isinstance(self.max_file_bytes, bool) or not isinstance(
            self.max_file_bytes, int
        ) or self.max_file_bytes <= 0:
            raise DocumentContentError("max_file_bytes must be a positive integer")
        if isinstance(self.max_total_bytes, bool) or not isinstance(
            self.max_total_bytes, int
        ) or self.max_total_bytes <= 0:
            raise DocumentContentError("max_total_bytes must be a positive integer")
        if self.on_limit not in {"error", "omit"}:
            raise DocumentContentError("on_limit must be one of: error, omit")

        self.include = include
        self.exclude = exclude
        self._include_regex = tuple(_compile_glob(value) for value in include)
        self._exclude_regex = tuple(_compile_glob(value) for value in exclude)

    @classmethod
    def from_config(cls, config: Config) -> DocumentContentPolicy:
        return cls(
            include=tuple(getattr(config, "document_content_include", ())),
            exclude=tuple(getattr(config, "document_content_exclude", ())),
            max_file_bytes=getattr(
                config, "document_content_max_file_bytes", DEFAULT_MAX_FILE_BYTES
            ),
            max_total_bytes=getattr(
                config, "document_content_max_total_bytes", DEFAULT_MAX_TOTAL_BYTES
            ),
            on_limit=getattr(config, "document_content_on_limit", "error"),
        )

    def should_store(self, rel_path: str) -> bool:
        path = _relative_posix(rel_path, "rel_path")
        if not self._include_regex:
            return False
        if any(pattern.fullmatch(path) for pattern in self._exclude_regex):
            return False
        return any(pattern.fullmatch(path) for pattern in self._include_regex)

    def validate_file(self, path: Path, rel_path: str | None = None) -> bool:
        try:
            size = path.stat().st_size
        except OSError as exc:
            raise DocumentContentError(f"cannot inspect document {path}: {exc}") from exc
        return self.validate_file_size(size, rel_path or str(path))

    def validate_file_size(self, size: int, rel_path: str) -> bool:
        """Validate the byte count observed from the actual opened snapshot."""
        if isinstance(size, bool) or not isinstance(size, int) or size < 0:
            raise DocumentContentError("document file size must be non-negative")
        return self._validate_size(size, rel_path)

    def validate_content(self, content: str, rel_path: str | None = None) -> bool:
        if not isinstance(content, str):
            raise DocumentContentError("document content must be text")
        return self._validate_size(
            utf8_size(content), rel_path or "document content"
        )

    def _validate_size(self, size: int, label: str) -> bool:
        if size <= self.max_file_bytes:
            return True
        if self.on_limit == "omit":
            return False
        raise DocumentContentLimitError(
            f"selected document {label!r} is {size} bytes; "
            f"max_file_bytes is {self.max_file_bytes}"
        )