// ========= 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 { createAsyncContext } from '../utils/async_context.ts'
import { OpRecord } from './record.ts'

interface RecordingState {
  records: OpRecord[]
  virtualPrefix: string
}

const storage = createAsyncContext<RecordingState>()

export async function runWithRecording<T>(fn: () => Promise<T>): Promise<[T, OpRecord[]]> {
  const state: RecordingState = { records: [], virtualPrefix: '' }
  const value = await storage.run(state, fn)
  return [value, state.records]
}

export function setVirtualPrefix(prefix: string): void {
  const state = storage.getStore()
  if (state !== undefined) state.virtualPrefix = prefix
}

export function record(
  op: string,
  path: string,
  source: string,
  nbytes: number,
  startMs: number,
): void {
  const state = storage.getStore()
  if (state === undefined) return
  const elapsed = Math.floor(performance.now() - startMs)
  state.records.push(
    new OpRecord({
      op,
      path: applyPrefix(state.virtualPrefix, path),
      source,
      bytes: nbytes,
      timestamp: Date.now(),
      durationMs: elapsed,
    }),
  )
}

export function recordStream(op: string, path: string, source: string): OpRecord | null {
  const state = storage.getStore()
  if (state === undefined) return null
  const rec = new OpRecord({
    op,
    path: applyPrefix(state.virtualPrefix, path),
    source,
    bytes: 0,
    timestamp: Date.now(),
    durationMs: 0,
  })
  state.records.push(rec)
  return rec
}

function applyPrefix(prefix: string, path: string): string {
  if (prefix !== '' && !path.startsWith(prefix)) {
    return prefix.replace(/\/+$/, '') + path
  }
  return path
}
