import type { AgentDomPayload } from '../ElementComment/element-dom-context'

/** Credential-like keys are replaced with `[redacted]`. Jason/Gavin may ask to send everything. */
const REDACT_KEY =
  /(?:^|[_-])(token|secret|password|authorization|api[_-]?key|id_token|access_token|refresh|jwt|session|cookie|bearer)(?:[_-]|$)/i

/** Matches a JWT's three base64url segments, e.g. `eyJhbGciOi....eyJzdWIiOi....SflKxw...`. */
const JWT_SHAPE = /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/
/** Long base64/base64url runs are usually opaque tokens rather than user-entered values. */
const TOKEN_LIKE_VALUE = /^[A-Za-z0-9_-]{40,}={0,2}$/

/** Per-key cap so query-cache blobs do not dominate the snapshot. */
const MAX_LOCAL_STORAGE_ENTRY_CHARS = 8_192
/** Total snapshot budget. Pi persist caches routinely exceed Express's 100kb json limit. */
const MAX_LOCAL_STORAGE_TOTAL_CHARS = 64_000

/** Catches secrets stored under a benign key name, where `REDACT_KEY` alone would miss them. */
function looksLikeSecretValue(value: string): boolean {
  return JWT_SHAPE.test(value) || TOKEN_LIKE_VALUE.test(value)
}

export type FeedbackUser = {
  id?: string
  email?: string
  name?: string
}

export type FeedbackContext = {
  app: string
  environment: string
  href: string
  userAgent: string
  capturedAt: string
  user?: FeedbackUser
  localStorage: Record<string, string>
}

export type FeedbackFormPayload = {
  message: string
  screenshots?: File[]
  audio?: File
  /** One file, or every clip when the session recorded more than once. */
  screenRecording?: File | File[]
  /** Queued select-element instructions for the agent. */
  elementComments?: AgentDomPayload[]
}

export type FeedbackWidgetPayload = FeedbackFormPayload & {
  context: FeedbackContext
}

export type FeedbackFileMeta = {
  name: string
  type: string
  size: number
}

export type FeedbackPayloadLog = {
  message: string
  context: FeedbackContext
  screenshots?: FeedbackFileMeta[]
  audio?: FeedbackFileMeta
  screenRecording?: FeedbackFileMeta | FeedbackFileMeta[]
  elementComments?: AgentDomPayload[]
}

function fileMeta(file?: File): FeedbackFileMeta | undefined {
  if (!file) return undefined
  return { name: file.name, type: file.type, size: file.size }
}

function recordingMeta(
  recording?: File | File[],
): FeedbackFileMeta | FeedbackFileMeta[] | undefined {
  if (!recording) return undefined
  const files = Array.isArray(recording) ? recording : [recording]
  if (files.length === 0) return undefined
  const metas = files.map((file) => ({ name: file.name, type: file.type, size: file.size }))
  return Array.isArray(recording) ? metas : metas[0]
}

/** JSON-safe view of the payload for DevTools. File bytes are omitted. */
export function describeFeedbackPayload(payload: FeedbackWidgetPayload): FeedbackPayloadLog {
  return {
    message: payload.message,
    context: payload.context,
    screenshots: payload.screenshots?.map((file) => ({
      name: file.name,
      type: file.type,
      size: file.size,
    })),
    audio: fileMeta(payload.audio),
    screenRecording: recordingMeta(payload.screenRecording),
    elementComments: payload.elementComments ?? [],
  }
}

export function snapshotLocalStorage(
  storage: Pick<Storage, 'length' | 'key' | 'getItem'> = window.localStorage,
): Record<string, string> {
  const entries: Record<string, string> = {}
  let totalChars = 0
  for (let index = 0; index < storage.length; index += 1) {
    const key = storage.key(index)
    if (!key) continue
    let value = '[redacted]'
    if (!REDACT_KEY.test(key)) {
      const stored = storage.getItem(key) ?? ''
      value = looksLikeSecretValue(stored) ? '[redacted]' : stored
    }
    if (value.length > MAX_LOCAL_STORAGE_ENTRY_CHARS) {
      value = `${value.slice(0, MAX_LOCAL_STORAGE_ENTRY_CHARS)}…[truncated]`
    }
    const added = key.length + value.length
    if (totalChars + added > MAX_LOCAL_STORAGE_TOTAL_CHARS) break
    entries[key] = value
    totalChars += added
  }
  return entries
}

export function buildFeedbackContext(input: {
  app: string
  environment: string
  user?: FeedbackUser
  href?: string
  userAgent?: string
  capturedAt?: string
  localStorage?: Record<string, string>
}): FeedbackContext {
  return {
    app: input.app,
    environment: input.environment,
    href: input.href ?? window.location.href,
    userAgent: input.userAgent ?? navigator.userAgent,
    capturedAt: input.capturedAt ?? Temporal.Now.instant().toString(),
    user: input.user,
    localStorage: input.localStorage ?? snapshotLocalStorage(),
  }
}
