// ========= 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 { S3Accessor } from '../../../accessor/s3.ts'
import { resolveGlob } from '../../../core/s3/glob.ts'
import { read as s3Read } from '../../../core/s3/read.ts'
import { IOResult, type ByteSource } from '../../../io/types.ts'
import { ResourceName, type PathSpec } from '../../../types.ts'
import { command, type CommandFnResult, type CommandOpts } from '../../config.ts'
import { specOf } from '../../spec/builtins.ts'
import { compareKeys, sortKey, type SortKeyOptions } from '../sort_helper.ts'
import { readStdinAsync } from '../utils/stream.ts'

const ENC = new TextEncoder()
const DEC = new TextDecoder('utf-8', { fatal: false })

function parseKeyOptions(flags: Record<string, string | boolean>): SortKeyOptions {
  return {
    keyField: typeof flags.k === 'string' ? Number.parseInt(flags.k, 10) : null,
    fieldSep: typeof flags.t === 'string' ? flags.t : null,
    ignoreCase: flags.f === true,
    numeric: flags.n === true,
    humanNumeric: flags.h === true,
    version: flags.V === true,
    month: flags.M === true,
  }
}

function sortAndDedupe(
  lines: string[],
  opts: SortKeyOptions,
  reverse: boolean,
  unique: boolean,
): string[] {
  const keyed = lines.map((l) => ({ l, k: sortKey(l, opts) }))
  keyed.sort((a, b) => compareKeys(a.k, b.k))
  let sorted = keyed.map((x) => x.l)
  if (reverse) sorted.reverse()
  if (unique) {
    const seen = new Set<string>()
    sorted = sorted.filter((l) => {
      if (seen.has(l)) return false
      seen.add(l)
      return true
    })
  }
  return sorted
}

function splitLinesNoEnds(text: string): string[] {
  if (text === '') return []
  const stripped = text.endsWith('\n') ? text.slice(0, -1) : text
  return stripped.split('\n')
}

async function sortCommand(
  accessor: S3Accessor,
  paths: PathSpec[],
  _texts: string[],
  opts: CommandOpts,
): Promise<CommandFnResult> {
  const keyOpts = parseKeyOptions(opts.flags)
  const reverse = opts.flags.r === true
  const unique = opts.flags.u === true
  let allLines: string[] = []
  if (paths.length > 0) {
    const resolved = await resolveGlob(accessor, paths, opts.index ?? undefined)
    const first = resolved[0]
    if (first === undefined) return [null, new IOResult()]
    const data = DEC.decode(await s3Read(accessor, first, opts.index ?? undefined))
    allLines = splitLinesNoEnds(data)
  } else {
    const raw = await readStdinAsync(opts.stdin)
    if (raw === null) {
      return [null, new IOResult({ exitCode: 1, stderr: ENC.encode('sort: missing operand\n') })]
    }
    allLines = splitLinesNoEnds(DEC.decode(raw))
  }
  const sorted = sortAndDedupe(allLines, keyOpts, reverse, unique)
  const output = sorted.join('\n')
  const out: ByteSource = output === '' ? new Uint8Array(0) : ENC.encode(output + '\n')
  return [out, new IOResult()]
}

export const S3_SORT = command({
  name: 'sort',
  resource: ResourceName.S3,
  spec: specOf('sort'),
  fn: sortCommand,
})
