// Licensed to Apache Software Foundation (ASF) under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Apache Software Foundation (ASF) licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

syntax = "proto3";

package banyandb.fodc.v1;

import "banyandb/common/v1/common.proto";
import "banyandb/database/v1/database.proto";
import "banyandb/database/v1/rpc.proto";
import "google/protobuf/timestamp.proto";

option go_package = "github.com/apache/skywalking-banyandb/api/proto/banyandb/fodc/v1";

service FODCService {
  // Bi-directional stream for agent registration and heartbeat
  rpc RegisterAgent(stream RegisterAgentRequest) returns (stream RegisterAgentResponse);

  // Bi-directional stream for metrics
  // Agent sends StreamMetricsRequest (metrics data), Proxy sends StreamMetricsResponse (metrics requests)
  rpc StreamMetrics(stream StreamMetricsRequest) returns (stream StreamMetricsResponse);

  // Bi-directional stream for cluster topology
  rpc StreamClusterTopology(stream StreamClusterTopologyRequest) returns (stream StreamClusterTopologyResponse);

  // Bi-directional stream for lifecycle data
  rpc StreamLifecycle(stream StreamLifecycleRequest) returns (stream StreamLifecycleResponse);

  // Bi-directional stream for crash diagnostics
  // Agent sends StreamCrashDiagnosticsRequest (panic collections), Proxy sends StreamCrashDiagnosticsResponse (requests)
  rpc StreamCrashDiagnostics(stream StreamCrashDiagnosticsRequest) returns (stream StreamCrashDiagnosticsResponse);

  // Bi-directional stream for memory-pressure pprof profiles.
  // Proxy drives via StreamPressureProfilesResponse (list metadata, or fetch one
  // profile's bytes); agent replies with StreamPressureProfilesRequest (metadata
  // records, or binary chunks).
  rpc StreamPressureProfiles(stream StreamPressureProfilesRequest) returns (stream StreamPressureProfilesResponse);
}

message RegisterAgentRequest {
  string node_role = 1;
  map<string, string> labels = 2;
  string pod_name = 4;
  repeated string container_names = 5;
}

message RegisterAgentResponse {
  bool success = 1;
  string message = 2;
  int64 heartbeat_interval_seconds = 3;
  string agent_id = 4;
}

message StreamMetricsRequest {
  repeated Metric metrics = 1;
  google.protobuf.Timestamp timestamp = 2;
}

// MetricType represents the Prometheus metric type.
enum MetricType {
  METRIC_TYPE_UNSPECIFIED = 0;
  METRIC_TYPE_GAUGE = 1;
  METRIC_TYPE_COUNTER = 2;
  METRIC_TYPE_HISTOGRAM = 3;
  METRIC_TYPE_SUMMARY = 4;
  METRIC_TYPE_UNTYPED = 5;
}

message Metric {
  string name = 1;
  map<string, string> labels = 2;
  double value = 3;
  string description = 4;
  google.protobuf.Timestamp timestamp = 5;
  MetricType type = 6;
}

message StreamMetricsResponse {
  google.protobuf.Timestamp start_time = 1; // Optional start time for time window
  google.protobuf.Timestamp end_time = 2; // Optional end time for time window
}

message Call {
  string id = 1;
  string target = 2;
  string source = 3;
}

message Topology {
  repeated banyandb.database.v1.Node nodes = 1;
  repeated Call calls = 2;
}

message StreamClusterTopologyRequest {
  google.protobuf.Timestamp timestamp = 1;
  Topology topology = 2;
}

message StreamClusterTopologyResponse {
  // Request topology from agent
  bool request_topology = 1;
}

message StreamLifecycleRequest {
  google.protobuf.Timestamp timestamp = 1;
  string pod_name = 2;
  LifecycleData lifecycle_data = 3;
}

message StreamLifecycleResponse {
  bool request_lifecycle = 1;
}

message LifecycleData {
  repeated LifecycleReport reports = 1;
  repeated GroupLifecycleInfo groups = 2;
}

message GroupLifecycleInfo {
  string name = 1;
  string catalog = 2;
  banyandb.common.v1.ResourceOpts resource_opts = 3;
  repeated banyandb.database.v1.DataInfo data_info = 4;
  // errors lists every failure observed while collecting data_info for this
  // group: top-level CollectDataInfo failures (GetGroup, missing collector,
  // dial failure -- prefixed "top-level: ") and per-node broadcast failures
  // (prefixed "future error: ", "node error: ", "broadcast failed: ").
  // Combined with len(data_info), consumers can tell the following four
  // states apart:
  //   - data_info empty && errors empty       -> no nodes reported (group inactive)
  //   - data_info empty && errors non-empty   -> total failure
  //   - data_info non-empty && errors empty   -> full success
  //   - data_info non-empty && errors non-empty -> partial failure
  repeated string errors = 5;
}

message LifecycleReport {
  string filename = 1;
  string report_json = 2;
}

message CrashBreadcrumb {
  google.protobuf.Timestamp time = 1;
  string stage = 2;
  string component = 3;
  map<string, string> fields = 4;
}

message CrashPanicRecord {
  google.protobuf.Timestamp occurred_at = 1;
  string component = 2;
  string panic_value = 3;
  bool recovered = 4;
  string goroutine_stack = 5;
  repeated CrashBreadcrumb breadcrumbs = 6;
  map<string, string> process_metadata = 7;
}

message StreamCrashDiagnosticsRequest {
  google.protobuf.Timestamp fetched_at = 1;
  string source_endpoint = 2;
  string artifact_dir = 3;
  CrashPanicRecord panic_record = 4;
  repeated string files = 5;
}

message StreamCrashDiagnosticsResponse {
  // Request crash diagnostics from agent
  bool request_diagnostics = 1;
}

// One pprof profile inside a capture event (metadata only, no bytes).
message PressureProfileInfo {
  string type = 1; // "heap" | "goroutine"
  string filename = 2; // base name, e.g. "heap.pprof"
  string filepath = 3; // absolute path on the agent's disk, e.g. /tmp/pressure-profiles/20260627T101112.000000000Z/heap.pprof
  string format = 4; // "pprof" (gzip-compressed protobuf)
  int64 size_bytes = 5; // on-disk size
}

// Metadata for one capture event (no bytes). pod/role are NOT carried here:
// the proxy enriches them from the registered AgentIdentity, same as crash.
message PressureProfileRecord {
  string profile_id = 1; // = event directory name (UTC ns timestamp)
  google.protobuf.Timestamp captured_at = 2;
  string source_endpoint = 3; // pprof endpoint pulled, e.g. http://localhost:6060
  uint64 rss_bytes = 4; // RSS at trigger (process_resident_memory_bytes); top-N sort key
  uint64 cgroup_limit_bytes = 5; // cgroup memory.max
  uint32 trigger_percent = 6; // configured threshold percent (e.g. 75)
  uint64 threshold_bytes = 7; // cgroup_limit_bytes * trigger_percent / 100
  repeated PressureProfileInfo profiles = 8;
}

// One slice of a profile's bytes during download.
message PressureProfileChunk {
  string request_id = 1; // echoes FetchPressureProfile.request_id -- correlates this chunk stream to its fetch
  string profile_id = 2;
  string type = 3; // "heap" | "goroutine"
  bytes data = 4; // a bounded slice (e.g. <= 1MB)
  bool last = 5; // true on the final chunk
  string error = 6; // non-empty if the file cannot be served (e.g. evicted / not found)
}

// Agent -> Proxy: either a metadata record (answer to list_profiles) or a byte
// chunk (answer to fetch_profile).
message StreamPressureProfilesRequest {
  oneof payload {
    PressureProfileRecord record = 1;
    ListComplete list_complete = 2;
    PressureProfileChunk chunk = 3;
  }
}

// Agent -> Proxy: sent once after all records for a ListProfiles request have been
// streamed (including the zero-record case), so the proxy knows the agent is done
// without waiting out a fixed window.
message ListComplete {
  string request_id = 1; // echoes ListProfiles.request_id
}

message FetchPressureProfile {
  string request_id = 1; // proxy-generated per fetch; echoed back in every PressureProfileChunk to correlate
  string profile_id = 2;
  string type = 3; // "heap" | "goroutine"
  string filepath = 4; // the absolute path the agent reported in PressureProfileInfo.filepath; agent opens it AFTER validating it is within --pressure-profiler-dir
}

// Proxy -> Agent: either "stream all your metadata" or "stream one profile's bytes".
message StreamPressureProfilesResponse {
  oneof command {
    ListProfiles list_profiles = 1;
    FetchPressureProfile fetch_profile = 2;
  }
}

// Proxy -> Agent: stream all capture-event metadata for this request id.
message ListProfiles {
  string request_id = 1; // proxy-generated per list; echoed back in ListComplete to correlate
}

// GroupLifecycleService provides group lifecycle information from liaison nodes.
// Registered on the internal gRPC server so FODC agent can access it.
service GroupLifecycleService {
  // InspectAll lists all groups and returns their full lifecycle info in one call.
  rpc InspectAll(InspectAllRequest) returns (InspectAllResponse);
}

message InspectAllRequest {}

message InspectAllResponse {
  repeated GroupLifecycleInfo groups = 1;
}
