syntax = "proto3";

package sms;

// Task status enumeration / 任务状态枚举
enum TaskStatus {
  TASK_STATUS_UNKNOWN = 0;      // Unknown status / 未知状态
  TASK_STATUS_REGISTERED = 1;   // Task is registered / 任务已注册
  TASK_STATUS_ACTIVE = 2;       // Task is active / 任务活跃
  TASK_STATUS_INACTIVE = 3;     // Task is inactive / 任务非活跃
}

// Task priority enumeration / 任务优先级枚举
enum TaskPriority {
  TASK_PRIORITY_UNKNOWN = 0;  // Unknown priority / 未知优先级
  TASK_PRIORITY_LOW = 1;      // Low priority / 低优先级
  TASK_PRIORITY_NORMAL = 2;   // Normal priority / 普通优先级
  TASK_PRIORITY_HIGH = 3;     // High priority / 高优先级
  TASK_PRIORITY_URGENT = 4;   // Urgent priority / 紧急优先级
}

// Executable type / 可执行类型
enum ExecutableType {
  EXECUTABLE_TYPE_UNKNOWN = 0;
  EXECUTABLE_TYPE_BINARY = 1;
  EXECUTABLE_TYPE_SCRIPT = 2;
  EXECUTABLE_TYPE_CONTAINER = 3;
  EXECUTABLE_TYPE_WASM = 4;
  EXECUTABLE_TYPE_PROCESS = 5;
}

// Executable descriptor / 可执行描述
message TaskExecutable {
  ExecutableType type = 1;          // Type of executable / 可执行类型
  string uri = 2;                    // Canonical URI (e.g., docker://image:tag, http://...) / 规范URI
  string name = 3;                   // Local name or alias / 本地名称或别名
  string checksum_sha256 = 4;        // Optional integrity checksum / 可选完整性校验
  repeated string args = 5;          // Default arguments / 默认参数
  map<string, string> env = 6;       // Default environment variables / 默认环境变量
}

// Task definition / 任务定义
message Task {
  string task_id = 1;                    // Unique task identifier (UUID v4, server-assigned) / 唯一任务标识符（UUID v4，由服务器分配）
  string name = 2;                       // Task name / 任务名称
  string description = 3;                // Task description / 任务描述
  TaskStatus status = 4;                 // Current task status / 当前任务状态
  TaskPriority priority = 5;             // Task priority / 任务优先级
  string node_uuid = 6;                  // Node UUID where task is registered / 任务注册的节点UUID
  string endpoint = 7;                   // Task endpoint URL / 任务端点URL
  string version = 8;                    // Task version / 任务版本
  repeated string capabilities = 9;      // Task capabilities / 任务能力
  int64 registered_at = 10;              // Task registration timestamp / 任务注册时间戳
  int64 last_heartbeat = 11;             // Last heartbeat timestamp / 最后心跳时间戳
  map<string, string> metadata = 12;     // Additional task metadata / 额外任务元数据
  map<string, string> config = 13;       // Task configuration / 任务配置
  TaskExecutable executable = 14;        // Executable descriptor / 可执行描述
  repeated string result_uris = 15;      // URIs of execution results / 执行结果的URI列表
  string last_result_uri = 16;           // URI of the last execution result / 最近一次执行结果的URI
  string last_result_status = 17;        // Status of the last execution (completed/failed) / 最近一次执行状态（completed/failed）
  int64 last_completed_at = 18;          // Timestamp of last completion / 最近一次完成时间戳
  map<string, string> last_result_metadata = 19; // Metadata of last result / 最近一次结果的元数据
}

// Task registration request / 任务注册请求
message RegisterTaskRequest {
  string name = 1;                       // Task name / 任务名称
  string description = 2;                // Task description / 任务描述
  TaskPriority priority = 3;             // Task priority / 任务优先级
  string node_uuid = 4;                  // Node UUID where task is registered / 任务注册的节点UUID
  string endpoint = 5;                   // Task endpoint URL / 任务端点URL
  string version = 6;                    // Task version / 任务版本
  repeated string capabilities = 7;      // Task capabilities / 任务能力
  map<string, string> metadata = 8;      // Additional task metadata / 额外任务元数据
  map<string, string> config = 9;        // Task configuration / 任务配置
  TaskExecutable executable = 10;        // Executable descriptor / 可执行描述
}

// Resolve task by endpoint / 通过 endpoint 解析任务
message ResolveEndpointRequest {
  string endpoint = 1; // Endpoint name / Endpoint 名称
}

message ResolveEndpointResponse {
  bool found = 1; // Whether task is found / 是否找到任务
  Task task = 2;  // Task details / 任务详情
}

// Task registration response / 任务注册响应
message RegisterTaskResponse {
  bool success = 1;                      // Whether registration was successful / 注册是否成功
  string message = 2;                    // Response message / 响应消息
  string task_id = 3;                    // Assigned task ID (UUID v4, present only if success) / 分配的任务ID（UUID v4，仅在成功时返回）
  Task task = 4;                         // Registered task details / 注册的任务详情
}

// Task event kind / 任务事件类型
enum TaskEventKind {
  TASK_EVENT_KIND_UNKNOWN = 0;
  TASK_EVENT_KIND_CREATE = 1;
  TASK_EVENT_KIND_UPDATE = 2;
  TASK_EVENT_KIND_CANCEL = 3;
}

// Task event for subscription / 任务事件（用于订阅）
message TaskEvent {
  int64 event_id = 1;           // Monotonic event id per node / 每节点单调递增事件ID
  int64 ts = 2;                 // Event timestamp (epoch seconds) / 事件时间戳
  string node_uuid = 3;         // Target node UUID / 目标节点UUID
  string task_id = 4;           // Task ID / 任务ID
  TaskEventKind kind = 5;       // Event kind / 事件类型
  optional string execution_id = 7;         // Optional execution identifier / 可选的执行标识符
}

// Subscribe request with optional resume position / 订阅请求（可带断点续传位置）
message SubscribeTaskEventsRequest {
  string node_uuid = 1;         // Node UUID to subscribe / 订阅的节点UUID
  int64 last_event_id = 2;      // Last processed id to resume from / 已处理的最后事件ID（从此之后恢复）
}

// Ack response / 确认响应
message AckResponse { bool ok = 1; }

// List tasks request / 列出任务请求
message ListTasksRequest {
  string node_uuid = 1;                  // Filter by node UUID (optional) / 按节点UUID过滤（可选）
  TaskStatus status_filter = 2;          // Filter by status (optional) / 按状态过滤（可选）
  TaskPriority priority_filter = 3;      // Filter by priority (optional) / 按优先级过滤（可选）
  int32 limit = 4;                       // Maximum number of tasks to return / 返回的最大任务数
  int32 offset = 5;                      // Offset for pagination / 分页偏移量
}

// List tasks response / 列出任务响应
message ListTasksResponse {
  repeated Task tasks = 1;               // List of tasks / 任务列表
  int32 total_count = 2;                 // Total number of tasks / 任务总数
}

// Get task request / 获取任务请求
message GetTaskRequest {
  string task_id = 1;                    // Task ID / 任务ID
}

// Get task response / 获取任务响应
message GetTaskResponse {
  bool found = 1;                        // Whether task was found / 是否找到任务
  Task task = 2;                         // Task details / 任务详情
}

// Unregister task request / 注销任务请求
message UnregisterTaskRequest {
  string task_id = 1;                    // Task ID to unregister / 要注销的任务ID
  string reason = 2;                     // Reason for unregistration / 注销原因
}

// Unregister task response / 注销任务响应
message UnregisterTaskResponse {
  bool success = 1;                      // Whether unregistration was successful / 注销是否成功
  string message = 2;                    // Response message / 响应消息
  string task_id = 3;                    // Unregistered task ID / 已注销的任务ID
}

// Task service definition / 任务服务定义
service TaskService {
  // Register a new task / 注册新任务
  rpc RegisterTask(RegisterTaskRequest) returns (RegisterTaskResponse);
  
  // List tasks with optional filtering / 列出任务（可选过滤）
  rpc ListTasks(ListTasksRequest) returns (ListTasksResponse);
  
  // Get task details by ID / 根据ID获取任务详情
  rpc GetTask(GetTaskRequest) returns (GetTaskResponse);
  
  // Unregister a task / 注销任务
  rpc UnregisterTask(UnregisterTaskRequest) returns (UnregisterTaskResponse);

  // Subscribe task events for a node / 订阅节点任务事件
  rpc SubscribeTaskEvents(SubscribeTaskEventsRequest) returns (stream TaskEvent);

  // Resolve task by endpoint / 通过 endpoint 解析任务
  rpc ResolveEndpoint(ResolveEndpointRequest) returns (ResolveEndpointResponse);

  // Update task status (observed state) / 更新任务状态（观测态）
  rpc UpdateTaskStatus(UpdateTaskStatusRequest) returns (UpdateTaskStatusResponse);

  // Update task result fields / 更新任务结果字段
  rpc UpdateTaskResult(UpdateTaskResultRequest) returns (UpdateTaskResultResponse);
}

// Update task status request / 更新任务状态请求
message UpdateTaskStatusRequest {
  string task_id = 1;              // Task ID / 任务ID
  TaskStatus status = 2;           // New status / 新状态
  string node_uuid = 3;            // Reporting node UUID / 上报节点UUID
  uint64 status_version = 4;       // Monotonic status version / 单调递增状态版本
  int64 updated_at = 5;            // Update timestamp / 更新时间戳
  string reason = 6;               // Optional reason / 可选原因
}

// Update task status response / 更新任务状态响应
message UpdateTaskStatusResponse {
  bool success = 1;                // Whether update succeeded / 更新是否成功
  string message = 2;              // Response message / 响应消息
  Task task = 3;                   // Updated task / 已更新任务
}

// Update task result request / 更新任务结果请求
message UpdateTaskResultRequest {
  string task_id = 1;                        // Task ID / 任务ID
  string result_uri = 2;                     // Result URI / 结果URI
  string result_status = 3;                  // Result status (completed/failed) / 结果状态
  int64 completed_at = 4;                    // Completion timestamp / 完成时间戳
  map<string, string> result_metadata = 5;   // Result metadata / 结果元数据
}

// Update task result response / 更新任务结果响应
message UpdateTaskResultResponse {
  bool success = 1;                // Whether update succeeded / 更新是否成功
  string message = 2;              // Response message / 响应消息
  Task task = 3;                   // Updated task / 已更新任务
}
