# ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========

from collections.abc import AsyncIterator, Awaitable, Callable
from typing import Any

from mirage.types import FileStat, PathSpec
from mirage.utils.key_prefix import mount_key


def to_pathspec(path: Any, prefix: str = "") -> PathSpec:
    if isinstance(path, PathSpec):
        return path
    return PathSpec(virtual=path,
                    directory=path,
                    resource_path=mount_key(path, prefix))


# The call_* helpers adapt a bound op (accessor and index already bound,
# called as ``op(path)``) so grep/rg can walk with plain string keys.


async def call_readdir(
    readdir_fn: Callable[[PathSpec], Awaitable[list[str]]],
    path: str | PathSpec,
    prefix: str = "",
) -> list[str]:
    return await readdir_fn(to_pathspec(path, prefix))


async def call_stat(
    stat_fn: Callable[[PathSpec], Awaitable[FileStat]],
    path: str | PathSpec,
    prefix: str = "",
) -> FileStat:
    return await stat_fn(to_pathspec(path, prefix))


async def call_read_bytes(
    read_fn: Callable[[PathSpec], Awaitable[bytes]],
    path: str | PathSpec,
    prefix: str = "",
) -> bytes:
    return await read_fn(to_pathspec(path, prefix))


async def stream_from_bytes(
    read_fn: Callable[..., Any],
    accessor: Any,
    path: Any,
    index: Any = None,
    prefix: str = "",
) -> AsyncIterator[bytes]:
    # CommandIO-level adapter: raw ``(accessor, path, index)`` shape.
    yield await read_fn(accessor, to_pathspec(path, prefix), index)
