/**
 * Workflow-specific logging types and utilities
 */

import type { ExecutionLogLevel, ExecutionLogMessage } from '../base/logging'

// Workflow start/end log context
export interface WorkflowExecutionContext {
  type: 'workflow'
  contextType: 'workflow-execution'
  executionId: string
  workflowId: string
  workflowName?: string
  organizationId: string
  executionPath?: string[]
}

// Workflow failure log context
export interface WorkflowFailureContext {
  type: 'workflow'
  contextType: 'workflow-failure'
  executionId: string
  workflowId: string
  error: string
}

// Step started log context
export interface StepStartedContext {
  type: 'workflow'
  contextType: 'step-started'
  stepId: string
  stepStatus: 'started'
  input: unknown
  startTime: number // Explicit start timestamp for timeline
}

// Step completed log context
export interface StepCompletedContext {
  type: 'workflow'
  contextType: 'step-completed'
  stepId: string
  stepStatus: 'completed'
  output: unknown
  duration: number
  isTerminal: boolean
  startTime: number // Explicit start timestamp for timeline
  endTime: number // Explicit end timestamp for timeline
}

// Step failed log context
export interface StepFailedContext {
  type: 'workflow'
  contextType: 'step-failed'
  stepId: string
  stepStatus: 'failed'
  error: string
  duration: number
  startTime: number // Explicit start timestamp for timeline
  endTime: number // Explicit end timestamp for timeline
}

// Conditional routing log context
export interface ConditionalRouteContext {
  type: 'workflow'
  contextType: 'conditional-route'
  stepId: string
  target: string
  error?: string
}

// Execution path log context
export interface ExecutionPathContext {
  type: 'workflow'
  contextType: 'execution-path'
  executionPath: string[]
}

// Union of step contexts with stepStatus field
export type StepStatusContext = StepStartedContext | StepCompletedContext | StepFailedContext

// Union of all workflow log contexts
export type WorkflowLogContext =
  | WorkflowExecutionContext
  | WorkflowFailureContext
  | StepStartedContext
  | StepCompletedContext
  | StepFailedContext
  | ConditionalRouteContext
  | ExecutionPathContext

// Workflow execution log message (UI-specific interface)
export interface WorkflowLogMessage {
  level: ExecutionLogLevel
  message: string
  timestamp: number
  context?: WorkflowLogContext
}

/**
 * Type guard helper functions for context discrimination
 */

export function isWorkflowExecutionContext(ctx: WorkflowLogContext): ctx is WorkflowExecutionContext {
  return ctx.contextType === 'workflow-execution'
}

export function isWorkflowFailureContext(ctx: WorkflowLogContext): ctx is WorkflowFailureContext {
  return ctx.contextType === 'workflow-failure'
}

export function isStepStartedContext(ctx: WorkflowLogContext): ctx is StepStartedContext {
  // Check new contextType field or fall back to old stepStatus pattern for backwards compatibility
  return (
    ctx.contextType === 'step-started' ||
    ('stepStatus' in ctx && (ctx as StepStatusContext).stepStatus === 'started')
  )
}

export function isStepCompletedContext(ctx: WorkflowLogContext): ctx is StepCompletedContext {
  // Check new contextType field or fall back to old stepStatus pattern for backwards compatibility
  return (
    ctx.contextType === 'step-completed' ||
    ('stepStatus' in ctx && (ctx as StepStatusContext).stepStatus === 'completed')
  )
}

export function isStepFailedContext(ctx: WorkflowLogContext): ctx is StepFailedContext {
  // Check new contextType field or fall back to old stepStatus pattern for backwards compatibility
  return (
    ctx.contextType === 'step-failed' ||
    ('stepStatus' in ctx && (ctx as StepStatusContext).stepStatus === 'failed')
  )
}

export function isConditionalRouteContext(ctx: WorkflowLogContext): ctx is ConditionalRouteContext {
  // Check new contextType field or fall back to checking for target field for backwards compatibility
  return ctx.contextType === 'conditional-route' || ('target' in ctx && 'stepId' in ctx && !('stepStatus' in ctx))
}

export function isExecutionPathContext(ctx: WorkflowLogContext): ctx is ExecutionPathContext {
  return ctx.contextType === 'execution-path'
}

/**
 * Helper to check if context has step-related information
 */
export function isStepContext(
  ctx: WorkflowLogContext
): ctx is StepStartedContext | StepCompletedContext | StepFailedContext | ConditionalRouteContext {
  return (
    ctx.contextType === 'step-started' ||
    ctx.contextType === 'step-completed' ||
    ctx.contextType === 'step-failed' ||
    ctx.contextType === 'conditional-route'
  )
}

/**
 * Convert ExecutionLogMessage to WorkflowLogMessage for workflow context
 * Returns null for non-workflow logs
 */
export function toWorkflowLogMessage(log: ExecutionLogMessage): WorkflowLogMessage | null {
  // Convert logs with workflow context
  if (log.context?.type === 'workflow') {
    return {
      level: log.level,
      message: log.message,
      timestamp: log.timestamp,
      context: log.context as WorkflowLogContext
    }
  }

  // Convert user-level logs (no context or non-workflow context from step handlers)
  // Cast is safe: LogEntry renders any context object as expandable JSON
  return {
    level: log.level,
    message: log.message,
    timestamp: log.timestamp,
    context: log.context as WorkflowLogContext | undefined
  }
}

/**
 * Convert array of ExecutionLogMessages to WorkflowLogMessages
 * Filters out non-workflow logs
 */
export function toWorkflowLogMessages(logs: ExecutionLogMessage[]): WorkflowLogMessage[] {
  return logs
    .map(toWorkflowLogMessage)
    .filter((log): log is WorkflowLogMessage => log !== null)
}
