// Broker Gateway Service - FIX Order Routing Protocol
//
// This service handles all broker communication via FIX 4.2/4.4 protocol
// for order routing, execution management, and account state synchronization.

syntax = "proto3";

package broker_gateway;

// ============================================================================
// Broker Gateway Service
// ============================================================================

service BrokerGatewayService {
  // Route order to broker via FIX protocol
  rpc RouteOrder(RouteOrderRequest) returns (RouteOrderResponse);

  // Cancel existing order
  rpc CancelOrder(CancelOrderRequest) returns (CancelOrderResponse);

  // Get current account state (balance, margin, positions)
  rpc GetAccountState(GetAccountStateRequest) returns (GetAccountStateResponse);

  // Get all positions for account
  rpc GetPositions(GetPositionsRequest) returns (GetPositionsResponse);

  // Get FIX session status
  rpc GetSessionStatus(GetSessionStatusRequest) returns (GetSessionStatusResponse);

  // Stream real-time executions from broker
  rpc StreamExecutions(StreamExecutionsRequest) returns (stream ExecutionEvent);

  // Health check
  rpc HealthCheck(HealthCheckRequest) returns (HealthCheckResponse);

  // Server-streaming: polls GetAccountState at gateway level
  rpc StreamAccountState(StreamAccountStateRequest) returns (stream GetAccountStateResponse);

  // Server-streaming: polls GetSessionStatus at gateway level
  rpc StreamSessionStatus(StreamSessionStatusRequest) returns (stream GetSessionStatusResponse);
}

// ============================================================================
// Order Routing
// ============================================================================

message RouteOrderRequest {
  string symbol = 1;                    // ES, NQ, etc.
  OrderSide side = 2;                   // BUY, SELL
  double quantity = 3;                  // Number of contracts
  OrderType order_type = 4;             // MARKET, LIMIT, STOP, STOP_LIMIT
  optional double price = 5;            // Limit price (required for LIMIT orders)
  optional double stop_price = 6;       // Stop price (required for STOP orders)
  string account_id = 7;                // AMP account identifier
  map<string, string> metadata = 8;     // Strategy, model_name, etc.
}

message RouteOrderResponse {
  string broker_order_id = 1;           // Broker-assigned OrderID (Tag 37, filled after ack)
  string client_order_id = 2;           // Our ClOrdID (Tag 11)
  OrderStatus status = 3;               // PENDING_SUBMIT, SUBMITTED, etc.
  int64 submitted_at = 4;               // Timestamp (nanoseconds)
  string message = 5;                   // Success/error message
}

message CancelOrderRequest {
  string client_order_id = 1;           // Order to cancel
  string account_id = 2;                // Account verification
}

message CancelOrderResponse {
  bool success = 1;
  string message = 2;
  OrderStatus new_status = 3;           // CANCEL_PENDING, CANCELLED, etc.
}

// ============================================================================
// Account & Position Management
// ============================================================================

message GetAccountStateRequest {
  string account_id = 1;
}

message GetAccountStateResponse {
  string account_id = 1;
  double cash_balance = 2;
  double equity = 3;
  double margin_used = 4;
  double margin_available = 5;
  double buying_power = 6;
  double unrealized_pnl = 7;
  double realized_pnl = 8;
  int64 last_updated = 9;               // Timestamp (nanoseconds)
}

message GetPositionsRequest {
  string account_id = 1;
  optional string symbol = 2;           // Filter by symbol (optional)
}

message GetPositionsResponse {
  repeated Position positions = 1;
  double total_equity = 2;
  double total_exposure = 3;
  double leverage_ratio = 4;
  int64 timestamp = 5;
}

message Position {
  string symbol = 1;
  double quantity = 2;                  // Positive = long, negative = short
  double average_price = 3;
  double market_value = 4;
  double unrealized_pnl = 5;
}

// ============================================================================
// Session Management
// ============================================================================

message GetSessionStatusRequest {
  optional string session_id = 1;       // Optional: default to active session
}

message GetSessionStatusResponse {
  string session_id = 1;
  SessionState state = 2;
  int64 sender_seq_num = 3;             // Current outgoing sequence
  int64 target_seq_num = 4;             // Expected incoming sequence
  int64 last_heartbeat_sent = 5;        // Timestamp (nanoseconds)
  int64 last_heartbeat_received = 6;    // Timestamp (nanoseconds)
  double heartbeat_rtt_ms = 7;          // Round-trip time in milliseconds
  int64 connected_at = 8;               // Timestamp (nanoseconds)
  map<string, string> details = 9;      // Additional session info
}

// ============================================================================
// Execution Streaming
// ============================================================================

message StreamExecutionsRequest {
  optional string account_id = 1;       // Filter by account
  optional string symbol = 2;           // Filter by symbol
}

message ExecutionEvent {
  string execution_id = 1;              // ExecID (Tag 17)
  string broker_order_id = 2;           // OrderID (Tag 37)
  string client_order_id = 3;           // ClOrdID (Tag 11)
  string symbol = 4;
  OrderSide side = 5;
  ExecutionType exec_type = 6;          // NEW, TRADE, CANCELED, REJECTED
  OrderStatus order_status = 7;         // Order status after this execution
  double last_qty = 8;                  // Quantity filled (Tag 32)
  double last_price = 9;                // Fill price (Tag 31)
  double cum_qty = 10;                  // Total filled (Tag 14)
  double avg_price = 11;                // Average fill price (Tag 6)
  int64 transact_time = 12;             // Execution timestamp
  optional string text = 13;            // Reject reason (if applicable)
}

// ============================================================================
// Health Check
// ============================================================================

message HealthCheckRequest {}

message HealthCheckResponse {
  bool healthy = 1;
  string message = 2;
  map<string, string> details = 3;
}

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

enum OrderSide {
  ORDER_SIDE_UNSPECIFIED = 0;
  ORDER_SIDE_BUY = 1;
  ORDER_SIDE_SELL = 2;
}

enum OrderType {
  ORDER_TYPE_UNSPECIFIED = 0;
  ORDER_TYPE_MARKET = 1;
  ORDER_TYPE_LIMIT = 2;
  ORDER_TYPE_STOP = 3;
  ORDER_TYPE_STOP_LIMIT = 4;
}

enum OrderStatus {
  ORDER_STATUS_UNSPECIFIED = 0;
  ORDER_STATUS_PENDING_SUBMIT = 1;
  ORDER_STATUS_SUBMITTED = 2;
  ORDER_STATUS_PARTIALLY_FILLED = 3;
  ORDER_STATUS_FILLED = 4;
  ORDER_STATUS_CANCEL_PENDING = 5;
  ORDER_STATUS_CANCELLED = 6;
  ORDER_STATUS_REJECTED = 7;
}

enum ExecutionType {
  EXECUTION_TYPE_UNSPECIFIED = 0;
  EXECUTION_TYPE_NEW = 1;               // Order accepted
  EXECUTION_TYPE_TRADE = 2;             // Partial or full fill
  EXECUTION_TYPE_CANCELED = 3;          // Order canceled
  EXECUTION_TYPE_REJECTED = 4;          // Order rejected
}

// Streaming request messages

message StreamAccountStateRequest {
  uint32 interval_seconds = 1; // 0 = server default (3s)
}

message StreamSessionStatusRequest {
  uint32 interval_seconds = 1; // 0 = server default (5s)
}

enum SessionState {
  SESSION_STATE_DISCONNECTED = 0;
  SESSION_STATE_CONNECTED = 1;
  SESSION_STATE_LOGGING_IN = 2;
  SESSION_STATE_ACTIVE = 3;
  SESSION_STATE_LOGGING_OUT = 4;
}
