/**
 * Base Execution Engine type definitions
 * Core types shared across all Execution Engine resources
 */

import { z } from 'zod'
import { IExecutionLogger } from './logging'
import type {
  SerializedAgentDefinition,
  SerializedWorkflowDefinition
} from '../../../platform/registry/serialized-types'
import type { AIUsageCollector } from '../../../operations/observability/ai-usage-collector'
import type { MetricsCollector } from '../../../operations/observability/metrics-collector'
import type { ResourceType, ResourceStatus, ExecutableResourceType } from '../../../platform/registry/types'

/**
 * Immutable execution metadata
 * Represents complete execution identity (who, what, when, where)
 * Shared across ExecutionContext and ExecutionLoggerContext to eliminate field duplication
 */
export interface ExecutionMetadata {
  executionId: string // Unique ID for this execution instance
  organizationId: string // Required for multi-tenant isolation and security
  organizationName: string // Required for resource lookup in registry
  resourceId: string // Required for observability and audit trails
  userId?: string // Optional: user context for audit trails (API keys, system executions may not have userId)
  sessionId?: string // Optional: only for session executions
  sessionTurnNumber?: number // Optional: only for session executions (maps to execution_logs.session_turn_number)
}

/**
 * Unified message event type - covers all message types in sessions
 * Replaces separate SessionTurnMessages and AgentActivityEvent mechanisms
 */
/**
 * Structured action metadata attached to assistant messages.
 * Frontend reads this instead of parsing text prefixes.
 */
export type AssistantAction =
  | { kind: 'navigate'; path: string; reason: string }
  | {
      kind: 'update_filters'
      timeRange: string | null
      statusFilter: string | null
      searchQuery: string | null
    }

export type MessageEvent =
  // User/Assistant text messages
  | { type: 'user_message'; text: string }
  | { type: 'assistant_message'; text: string; _action?: AssistantAction }

  // Agent lifecycle events
  | { type: 'agent:started' }
  | { type: 'agent:completed' }
  | { type: 'agent:error'; error: string }

  // Agent activity events (with metadata for UI)
  | { type: 'agent:reasoning'; iteration: number; reasoning: string }
  | { type: 'agent:tool_call'; toolName: string; args: Record<string, unknown> }
  | { type: 'agent:tool_result'; toolName: string; success: boolean; result?: unknown; error?: string }

/**
 * Execution context for all resources
 * Unified callback replaces SessionTurnMessages (removed)
 */
export interface ExecutionContext extends ExecutionMetadata {
  // Inherited: executionId, organizationId, organizationName, resourceId, userId, sessionId, sessionTurnNumber
  logger: IExecutionLogger // Required for observability and debugging
  signal?: AbortSignal // Future: cancellation support for long-running operations

  // Unified message event callback (immediate persistence + streaming)
  onMessageEvent?: (event: MessageEvent) => Promise<void>

  /** Called per iteration to write heartbeat + check stall status. Non-fatal if it throws. */
  onHeartbeat?: () => Promise<void>

  // Observability collectors (optional - injected by coordinators)
  aiUsageCollector?: AIUsageCollector // Tracks AI token usage and costs
  metricsCollector?: MetricsCollector // Tracks execution timing and ROI metrics

  // Nested execution tracking (Wave 2c - Agent Resource Invocation)
  parentExecutionId?: string // Parent execution ID for nested invocations
  executionDepth: number // Nesting depth: 0 = top-level, 1+ = nested

  // Integration credential tracking (for OAuth token refresh persistence)
  credentialName?: string // Credential name used for current integration call

  // Execution-scoped storage for large data (e.g., PDF buffers) that shouldn't be logged
  // Automatically garbage collected when execution context ends
  store: Map<string, unknown>
}

// Contract definition - validation schemas (Zod)
export interface Contract {
  inputSchema: z.ZodSchema // Required - use z.object({}) for no input
  outputSchema?: z.ZodSchema // Optional - if present, agent generates output
}

// Contract structure - serializable JSON Schema representation
export interface ContractStructure {
  inputSchema: unknown // JSON Schema representation
  outputSchema?: unknown // JSON Schema representation (optional for side-effect resources)
}

// Re-export resource types from registry (canonical source)
export type { ResourceType, ResourceStatus, ExecutableResourceType }

/**
 * NOTE: AIResource interface has been removed and replaced with ResourceDefinition
 * from registry/types.ts. All resources (executable and non-executable) now extend
 * the unified ResourceDefinition base interface.
 *
 * AgentConfig and WorkflowConfig now extend ResourceDefinition directly.
 * See packages/core/src/registry/types.ts for the base interface definition.
 */

// Generic/Unified Resource Structure type
// Each resource type (workflow, agent) implements its own specific structure
export type AIResourceDefinition = SerializedWorkflowDefinition | SerializedAgentDefinition

// UI color constants for resource types and statuses
export const ResourceStatusColors = {
  dev: 'var(--color-primary)',
  prod: 'var(--color-success)'
} as const
