// ========= 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. =========

import type { LanceDBAccessor } from '../../accessor/lancedb.ts'
import type { IndexCacheStore } from '../../cache/index/store.ts'
import { FileStat, FileType, PathSpec } from '../../types.ts'
import { imageTypeForExtension } from '../../utils/filetype.ts'
import { rstripSlash } from '../../utils/slash.ts'
import { read } from './read.ts'
import { ScopeLevel, detectScope } from './scope.ts'

function notFound(p: string): Error {
  const err = new Error(p) as Error & { code?: string }
  err.code = 'ENOENT'
  return err
}

function nameOf(spec: PathSpec): string {
  const stripped = rstripSlash(spec.virtual)
  const last = stripped.split('/').pop()
  return last === undefined || last === '' ? '/' : last
}

export async function stat(
  accessor: LanceDBAccessor,
  path: PathSpec | string,
  index?: IndexCacheStore,
): Promise<FileStat> {
  const spec = typeof path === 'string' ? PathSpec.fromStrPath(path) : path
  const config = accessor.config
  const scope = detectScope(spec, config)

  if (scope.level === ScopeLevel.UNKNOWN) throw notFound(spec.virtual)

  if (scope.table !== null) {
    const tables = await accessor.driver.listTables()
    if (!tables.includes(scope.table)) throw notFound(spec.virtual)
  }

  if (scope.level === ScopeLevel.ROOT || scope.level === ScopeLevel.GROUP_DIR) {
    return new FileStat({ name: nameOf(spec), type: FileType.DIRECTORY })
  }

  const fileType = scope.blob ? imageTypeForExtension(config.blobExt) : 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 !== undefined) {
    const lookup = await index.get(rstripSlash(spec.virtual))
    if (lookup.entry !== undefined && lookup.entry !== null && lookup.entry.size !== null) {
      return new FileStat({ name: nameOf(spec), size: lookup.entry.size, type: fileType })
    }
  }
  const data = await read(accessor, spec, index)
  return new FileStat({ name: nameOf(spec), size: data.length, type: fileType })
}
