from __future__ import annotations

from pathlib import Path

from ..config import mcp_config


def validate_and_read_file(
    file_path: str,
    file_name_override: str | None = None,
) -> tuple[bool, bytes | None, str, str]:
    """
    Validate and read a local file.
    Returns (ok, file_bytes, resolved_file_name, error_message).
    """
    if not file_path:
        return False, None, "", "filePath must be a non-empty string."

    resolved = Path(file_path).resolve()

    if not resolved.exists():
        return False, None, "", f"File not found: {resolved}"

    if not resolved.is_file():
        return False, None, "", f"Path is not a file: {resolved}"

    size = resolved.stat().st_size
    if size == 0:
        return False, None, "", "File cannot be empty."

    if size > mcp_config.max_file_size_bytes:
        limit_mb = mcp_config.max_file_size_bytes / (1024 * 1024)
        size_mb = size / (1024 * 1024)
        return False, None, "", f"File exceeds {limit_mb:.0f} MB limit ({size_mb:.1f} MB)."

    try:
        data = resolved.read_bytes()
    except OSError as exc:
        return False, None, "", f"Cannot read file: {exc}"

    name = file_name_override or resolved.name
    return True, data, name, ""
