import os

from fliiq.runtime.security import check_path_allowed

MAX_BYTES = 100_000  # 100KB cap


async def handler(params: dict) -> dict:
    """Read file contents with optional offset/limit."""
    path = params["path"]
    check_path_allowed(path)
    offset = params.get("offset") or 0
    limit = params.get("limit") or 300

    if not os.path.isfile(path):
        raise FileNotFoundError(f"File not found: {path}")

    # Detect binary files
    with open(path, "rb") as f:
        chunk = f.read(8192)
        if b"\x00" in chunk:
            raise ValueError(f"Binary file detected, cannot read: {path}")

    with open(path, "r", errors="replace") as f:
        lines = f.readlines()

    selected = lines[offset : offset + limit]

    # Format with line numbers
    numbered = []
    for i, line in enumerate(selected, start=offset + 1):
        numbered.append(f"{i}\t{line.rstrip()}")

    content = "\n".join(numbered)

    # Cap output size
    if len(content) > MAX_BYTES:
        content = content[:MAX_BYTES] + "\n... (truncated at 100KB)"

    return {"content": content}
