/**
 * Workflow Types Definition
 * Corresponds to backend Rust types in `common-contracts/src/messages.rs`
 * 
 * 遵循原则：
 * 1. 强类型约束：枚举和接口严格对应
 * 2. 单一来源：通过后端定义推导前端类型
 */

// ============================================================================
// Enums
// ============================================================================

export type TaskType = 'DataFetch' | 'DataProcessing' | 'Analysis';

export type TaskStatus = 
  | 'Pending'    // 等待依赖
  | 'Scheduled'  // 依赖满足，已下发给 Worker
  | 'Running'    // Worker 正在执行
  | 'Completed'  // 执行成功
  | 'Failed'     // 执行失败
  | 'Skipped';   // 因上游失败或策略原因被跳过

// ============================================================================
// Graph Structure (DAG)
// ============================================================================

export interface TaskNode {
  id: string;
  name: string;
  type: TaskType;
  initial_status: TaskStatus;
}

export interface TaskDependency {
  from: string;
  to: string;
}

export interface WorkflowDag {
  nodes: TaskNode[];
  edges: TaskDependency[];
}

// ============================================================================
// Events (Server-Sent Events Payloads)
// ============================================================================

/**
 * Base interface for all workflow events
 * Discriminated union based on 'type' field
 */
export type WorkflowEvent = 
  | {
      type: 'WorkflowStarted';
      payload: {
        timestamp: number;
        task_graph: WorkflowDag;
      };
    }
  | {
      type: 'TaskStateChanged';
      payload: {
        task_id: string;
        task_type: TaskType;
        status: TaskStatus;
        message: string | null;
        timestamp: number;
      };
    }
  | {
      type: 'TaskStreamUpdate';
      payload: {
        task_id: string;
        content_delta: string;
        index: number;
      };
    }
  | {
      type: 'WorkflowCompleted';
      payload: {
        result_summary: any; // JSON Value
        end_timestamp: number;
      };
    }
  | {
      type: 'WorkflowFailed';
      payload: {
        reason: string;
        is_fatal: boolean;
        end_timestamp: number;
      };
    }
  | {
      type: 'WorkflowStateSnapshot';
      payload: {
        timestamp: number;
        task_graph: WorkflowDag;
        tasks_status: Record<string, TaskStatus>;
        tasks_output: Record<string, string | null>;
      };
    };

// ============================================================================
// API Request/Response Types
// ============================================================================

export interface StartWorkflowRequest {
  symbol: string;
  market?: string;
  template_id: string;
}

export interface StartWorkflowResponse {
  request_id: string;
  symbol: string;
  market: string;
}

