// Import z for schema types
import type { z } from 'zod'

/**
 * Workflow-specific type definitions
 */

import type { ExecutionContext } from '../base/types'
import type { ResourceDefinition } from '../../../platform/registry/types'
import type { WorkflowResourceEntry } from '../../../organization-model/domains/resources'
import type { ResourceMetricsConfig } from '../../../operations/observability/types'
import type { ExecutionInterface } from '../interface/types'

// Workflow configuration
export interface WorkflowConfig extends ResourceDefinition {
  type: 'workflow'
  /** OM descriptor backing canonical identity and governance metadata. */
  resource?: WorkflowResourceEntry
}

export type DescriptorBackedWorkflowConfig = Omit<WorkflowConfig, 'resourceId' | 'type' | 'resource'> & {
  resource: WorkflowResourceEntry
}

// Workflow step definition
export interface WorkflowStepDefinition {
  id: string
  name: string
  description: string
}

// Step handler function type
export type StepHandler = (input: unknown, context: ExecutionContext) => Promise<unknown>

// Step type for flow control
export const StepType = {
  LINEAR: 'linear',
  CONDITIONAL: 'conditional'
} as const
export type StepType = (typeof StepType)[keyof typeof StepType]

// Next step configuration types
export interface LinearNext {
  type: 'linear'
  target: string
}

export interface ConditionalNext {
  type: 'conditional'
  routes: Array<{
    condition: (data: unknown) => boolean
    target: string
  }>
  default: string // Required to avoid ambiguity
}

export type NextConfig =
  | LinearNext // Go to specific step
  | ConditionalNext // Conditional routing
  | null // Explicitly end workflow

// Workflow step with graph-based flow
export interface WorkflowStep extends WorkflowStepDefinition {
  handler: StepHandler

  // I/O validation (BOTH REQUIRED for complete type safety)
  inputSchema: z.ZodSchema // Validates input from previous step or workflow
  outputSchema: z.ZodSchema // Validates output before next step

  next: NextConfig // Required - explicit flow decision for every step
}

// Workflow definition - pure configuration without instance state
// Used by registry to define workflows that can be instantiated
export interface WorkflowDefinition {
  config: WorkflowConfig
  contract: import('../base/types').Contract
  steps: Record<string, WorkflowStep>
  entryPoint: string

  /**
   * Metrics configuration for ROI calculations
   * Optional: Only needed if tracking automation savings
   */
  metricsConfig?: ResourceMetricsConfig

  /**
   * Execution interface configuration (optional)
   * If provided, workflow appears in Execution Runner UI
   */
  interface?: ExecutionInterface

  /**
   * Lead-gen processing stage this workflow implements (optional).
   * Must match a key in the platform lead-gen stage catalog.
   * Used by org-os graph derivation to surface workflow→stage edges and
   * by pipeline_config validation to confirm each catalog stage has an
   * implementing workflow before a list is activated.
   *
   * Example: stageImplemented: 'verified' on the email-verification workflow.
   */
  stageImplemented?: string
}

/**
 * Workflow timeline and observability types
 * Used for UI timeline visualization and backend processing
 */

import type { WorkflowLogMessage } from './logging'

/**
 * Workflow step state
 * Aggregates step context events with timing and logs
 */
export interface StepState {
  stepId: string
  stepName: string
  status: 'pending' | 'running' | 'completed' | 'failed'

  // Timeline visualization timing
  startTime?: number // From step-started context
  endTime?: number // From step-completed/failed context
  duration?: number // From step-completed/failed context

  // Step data
  input?: unknown
  output?: unknown
  error?: unknown
  logs: WorkflowLogMessage[]
}

/**
 * Complete workflow execution data for node visualization
 * Parsed from execution logs
 */
export interface WorkflowNodeVisualizerData {
  steps: StepState[]
  totalDuration: number
  isRunning: boolean
}

/**
 * Step data extracted from execution logs
 * Used to provide detailed step information in unified graph nodes
 */
export interface StepExecutionData {
  /** Final execution status for this step */
  status: 'pending' | 'running' | 'completed' | 'failed'

  /** Step execution duration in milliseconds */
  duration?: number

  /** Step input data */
  input?: unknown

  /** Step output data */
  output?: unknown

  /** Error data if step failed */
  error?: unknown

  /** Log messages from this step (reserved for future use) */
  logs?: unknown[]
}

/**
 * Execution path tracking state
 *
 * Tracks which steps have been executed and which edges were taken during workflow
 * execution. This state is built from SSE execution log events and used to compute
 * the visual dimming/highlighting of nodes and edges.
 *
 * Algorithm:
 * - `executedSteps` provides O(1) lookup for "has this step been reached?"
 * - `executedStepsOrdered` preserves execution order for edge inference
 * - `takenEdges` comes from `conditional-route` SSE events + linear step inference
 * - `currentStepId` tracks the actively running step for animation
 * - `stepStatusMap` provides final status for each executed step
 * - `stepDataMap` provides detailed execution data (duration, input, output, error)
 */
export interface ExecutionPathState {
  /** Set of step IDs that have been executed (O(1) lookup) */
  executedSteps: Set<string>

  /** Step IDs in execution order (for inferring linear edges) */
  executedStepsOrdered: string[]

  /** Set of edge IDs that were traversed (format: "edge-{source}-{target}") */
  takenEdges: Set<string>

  /** Currently running step ID (undefined if no step is running) */
  currentStepId?: string

  /** Map of step IDs to their final execution status */
  stepStatusMap?: Map<string, 'pending' | 'running' | 'completed' | 'failed'>

  /** Map of step IDs to their execution data (duration, input, output, error) */
  stepDataMap?: Map<string, StepExecutionData>
}
