# ========= 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 mirage.accessor.lancedb import LanceDBAccessor
from mirage.cache.index import NULL_INDEX, IndexCacheStore
from mirage.core.lancedb.query import table_exists
from mirage.core.lancedb.read import read
from mirage.core.lancedb.scope import (LanceDBGroupScope, LanceDBRowScope,
                                       ScopeLevel, detect_scope)
from mirage.types import FileStat, FileType, PathSpec
from mirage.utils.filetype import image_type_for_extension


def _name_of(path: PathSpec) -> str:
    stripped = path.virtual.rstrip("/")
    return stripped.rsplit("/", 1)[-1] or "/"


async def stat(
    accessor: LanceDBAccessor,
    path: PathSpec,
    index: IndexCacheStore = NULL_INDEX,
) -> FileStat:
    config = accessor.config
    scope = detect_scope(path, config)

    if scope.level == ScopeLevel.UNKNOWN:
        raise FileNotFoundError(path.virtual)

    if (isinstance(scope, (LanceDBGroupScope, LanceDBRowScope))
            and not await table_exists(accessor, scope.table)):
        raise FileNotFoundError(path.virtual)

    if scope.level in (ScopeLevel.ROOT, ScopeLevel.GROUP_DIR):
        return FileStat(name=_name_of(path), type=FileType.DIRECTORY)

    if not isinstance(scope, LanceDBRowScope):
        raise FileNotFoundError(path.virtual)
    if scope.blob:
        file_type = image_type_for_extension(config.blob_ext)
    else:
        file_type = FileType.TEXT
    # The row-dir readdir seeds exact card sizes; blob entries and a cold
    # index fall back to rendering the row, so the size is exact either way.
    if index is not None:
        lookup = await index.get(path.virtual.rstrip("/"))
        if lookup.entry is not None and lookup.entry.size is not None:
            return FileStat(name=_name_of(path),
                            size=lookup.entry.size,
                            type=file_type)
    data = await read(accessor, path, index)
    return FileStat(name=_name_of(path), size=len(data), type=file_type)
