// ========= 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 { mountPrefixOf } from '../../../utils/key_prefix.ts'
import type { LanceDBAccessor } from '../../../accessor/lancedb.ts'
import { searchRowsOutput } from '../../../core/lancedb/search.ts'
import { IOResult } from '../../../io/types.ts'
import type { PathSpec } from '../../../types.ts'
import { ResourceName } from '../../../types.ts'
import { command, type CommandFnResult, type CommandOpts, type ProvisionFn } from '../../config.ts'
import { exactZeroProvision } from '../generic_bind/provision.ts'
import { specOf } from '../../spec/builtins.ts'
import { defaultPaths } from '../utils/operands.ts'
import { FlagView } from '../../spec/types.ts'

const ENC = new TextEncoder()

async function searchCommand(
  accessor: LanceDBAccessor,
  paths: PathSpec[],
  texts: string[],
  opts: CommandOpts,
): Promise<CommandFnResult> {
  const query = texts[0]
  if (query === undefined || query === '') {
    return [null, new IOResult({ exitCode: 1, stderr: ENC.encode('search: query is required\n') })]
  }
  const fl = new FlagView(opts.flags, specOf('search'))
  const method = fl.asStr('method') ?? 'semantic'
  if (method !== 'semantic') {
    return [
      null,
      new IOResult({
        exitCode: 1,
        stderr: ENC.encode("search: only the 'semantic' method is supported\n"),
      }),
    ]
  }
  const target = defaultPaths(paths, opts.cwd)
  const mountPrefix =
    (target[0] === undefined
      ? undefined
      : mountPrefixOf(target[0].virtual, target[0].resourcePath)) ??
    opts.mountPrefix ??
    ''
  const topK = fl.asInt('top_k') ?? accessor.config.searchLimit
  const threshold = fl.asFloat('threshold') ?? 0
  try {
    const out = await searchRowsOutput(accessor, query, target, topK, threshold, mountPrefix)
    return [out, new IOResult()]
  } catch (err) {
    const msg = err instanceof Error ? err.message : String(err)
    return [null, new IOResult({ exitCode: 1, stderr: ENC.encode(`${msg}\n`) })]
  }
}

export const LANCEDB_SEARCH = command({
  name: 'search',
  resource: ResourceName.LANCEDB,
  spec: specOf('search'),
  fn: searchCommand,
  provision: exactZeroProvision as ProvisionFn,
})
