import type { HarnessEvent } from '../../lib/harness-types'

export interface AttemptLiveness {
  elapsedSecs: number
  lastActivity: string
  lastSignalAt: string
}

export interface AttemptUsageKnown {
  inputTokens: number
  outputTokens: number
  model: string
  costUsd?: number
  cachedTokens?: number
}

export interface AttemptUsageUnknown {
  unknown: true
  model: string
}

export type AttemptUsage = AttemptUsageKnown | AttemptUsageUnknown

export interface AttemptActivity {
  toolCalls?: number
  filesTouched?: string[]
  repeatedCommands?: string[][]
  failureFingerprint?: string
}

export interface AttemptRecord {
  attemptId: string
  task?: string
  phase?: string
  seat?: string
  account?: string
  model?: string
  wrapper?: string
  timeoutSecs: number
  promptPath?: string
  promptSha?: string
  causalInput?: string
  valid?: boolean
  verdict?: string
  replyPath?: string
  usage?: AttemptUsage
  liveness: AttemptLiveness | null
  activity?: AttemptActivity | null
  failureClass?: string
  taskDispatchCount?: number
  taskDispatchBudget?: number
}

const HEARTBEAT_GAP_MS = 180_000

export function isAttemptAlarmed(attempt: AttemptRecord, nowMs: number): boolean {
  if (!attempt.liveness) return false
  if (attempt.liveness.elapsedSecs > 2 * attempt.timeoutSecs) return true
  const lastSignalMs = Date.parse(attempt.liveness.lastSignalAt)
  if (!Number.isFinite(lastSignalMs)) return false
  return nowMs - lastSignalMs > HEARTBEAT_GAP_MS
}

export function shortAttemptId(attemptId: string): string {
  if (attemptId.length <= 12) return attemptId
  return attemptId.slice(-12)
}

export function wrapperLabel(wrapper: string | undefined): string {
  if (!wrapper) return 'not recorded'
  const parts = wrapper.split(/[/\\]/)
  return parts[parts.length - 1] || wrapper
}

export function attemptInProgress(attempt: AttemptRecord): boolean {
  return attempt.liveness !== null
}

export function attemptVerdictLabel(attempt: AttemptRecord): string {
  if (attemptInProgress(attempt)) return 'in progress'
  if (attempt.verdict !== undefined) return attempt.verdict
  if (attempt.valid === true) return 'valid'
  if (attempt.valid === false) return 'invalid'
  return 'not yet available'
}

export function elapsedTimeoutRatio(attempt: AttemptRecord): string | null {
  if (!attempt.liveness) return null
  return `${attempt.liveness.elapsedSecs}s / ${attempt.timeoutSecs}s`
}

export function isUsageUnknown(usage: AttemptUsage): usage is AttemptUsageUnknown {
  return 'unknown' in usage && usage.unknown === true
}

export interface QuarantineRecord {
  phase: string
  reason: string
}

export function extractQuarantine(events: HarnessEvent[]): QuarantineRecord | null {
  for (let i = events.length - 1; i >= 0; i -= 1) {
    const event = events[i]
    if (event.kind !== 'quarantine') continue
    return {
      phase: typeof event.payload.phase === 'string' ? event.payload.phase : 'not recorded',
      reason: typeof event.payload.reason === 'string' ? event.payload.reason : 'not recorded',
    }
  }
  return null
}
