/**
 * Trading Agents Types
 * Type definitions for Trading Agents (Atlas, Orion, Nova) integration
 * Aligned with backend trading-agents.client.ts and agents.service.ts
 * Updated: 2026-01-27
 */

// ============================================================================
// Agent Type Definitions
// ============================================================================

/**
 * Supported trading agent types
 * - atlas: Conservative trading strategy (long-term, low risk)
 * - orion: Balanced/moderate trading strategy
 * - nova: Aggressive trading strategy (high risk/reward)
 */
export type AgentType = 'atlas' | 'orion' | 'nova';

/**
 * Agent lifecycle status states
 */
export type AgentStatus = 'stopped' | 'starting' | 'running' | 'paused' | 'error';

/**
 * Display-friendly bot status for UI
 */
export type BotStatus = 'idle' | 'running' | 'paused' | 'stopped' | 'error' | 'unavailable';

/**
 * Trade side direction
 */
export type TradeSide = 'long' | 'short';

/**
 * Signal action direction
 */
export type SignalAction = 'buy' | 'sell' | 'hold';

// ============================================================================
// Agent Configuration
// ============================================================================

/**
 * Configuration for starting a trading agent
 */
export interface TradingBotConfig {
  /** Initial capital/equity for the agent */
  initialEquity: number;

  /** List of trading symbols (e.g., 'BTCUSDT', 'EURUSD') */
  symbols?: string[];

  /** Risk per trade as percentage (e.g., 2.0 = 2%) */
  riskPerTrade?: number;

  /** Maximum number of concurrent positions */
  maxPositions?: number;
}

// ============================================================================
// Agent Status & Metrics
// ============================================================================

/**
 * Current status of a trading agent
 */
export interface AgentStatusResponse {
  /** Agent identifier (atlas, orion, nova) */
  agent_name: AgentType;

  /** Current status of the agent */
  status: AgentStatus;

  /** Current equity/account balance */
  equity: number;

  /** Number of open positions */
  positions: number;

  /** Profit/Loss for the current day */
  today_pnl: number;

  /** Agent uptime in seconds */
  uptime_seconds: number;

  /** Timestamp of the last trade executed */
  last_trade_at?: string;

  /** Error message if status is 'error' */
  error_message?: string;
}

/**
 * Performance metrics for a trading agent
 */
export interface AgentMetrics {
  /** Total number of trades executed */
  total_trades: number;

  /** Number of profitable trades */
  winning_trades: number;

  /** Number of losing trades */
  losing_trades: number;

  /** Win rate as percentage (0-100) */
  win_rate: number;

  /** Total profit from winning trades */
  total_profit: number;

  /** Total loss from losing trades */
  total_loss: number;

  /** Net profit/loss */
  net_pnl: number;

  /** Maximum drawdown percentage */
  max_drawdown: number;

  /** Current drawdown percentage */
  current_drawdown: number;

  /** Sharpe ratio (risk-adjusted return) */
  sharpe_ratio?: number;

  /** Sortino ratio (downside risk-adjusted return) */
  sortino_ratio?: number;

  /** Profit factor (total profit / total loss) */
  profit_factor?: number;
}

/**
 * Frontend representation of a trading bot
 * Combines status and basic metrics for dashboard display
 */
export interface TradingBot {
  /** Unique identifier for the bot */
  id: string;

  /** Agent type name */
  name: AgentType;

  /** Display name for UI */
  displayName: string;

  /** Agent description/strategy type */
  description: string;

  /** Current bot status */
  status: BotStatus;

  /** Current account equity */
  equity: number;

  /** Number of open positions */
  positions: number;

  /** P&L for today */
  todayPnl: number;

  /** Extended metrics (optional) */
  metrics?: AgentMetrics;
}

// ============================================================================
// Positions
// ============================================================================

/**
 * Open trading position for an agent
 */
export interface AgentPosition {
  /** Position unique identifier */
  id: string;

  /** Trading symbol (e.g., 'BTCUSDT') */
  symbol: string;

  /** Position direction (long/short) */
  side: TradeSide;

  /** Position size/quantity */
  quantity: number;

  /** Entry price */
  entry_price: number;

  /** Current market price */
  current_price: number;

  /** Unrealized P&L in currency */
  unrealized_pnl: number;

  /** Unrealized P&L percentage */
  unrealized_pnl_percent: number;

  /** Stop loss price */
  stop_loss?: number;

  /** Take profit price */
  take_profit?: number;

  /** Position open timestamp (ISO 8601) */
  opened_at: string;
}

/**
 * Frontend-friendly position display
 */
export interface BotPosition extends AgentPosition {
  /** Display-friendly P&L string */
  pnlDisplay?: string;

  /** Position status color (for UI styling) */
  statusColor?: 'green' | 'red' | 'neutral';
}

// ============================================================================
// Trades & History
// ============================================================================

/**
 * Closed trade from agent history
 */
export interface AgentTrade {
  /** Trade unique identifier */
  id: string;

  /** Trading symbol (e.g., 'BTCUSDT') */
  symbol: string;

  /** Trade direction (long/short) */
  side: TradeSide;

  /** Quantity traded */
  quantity: number;

  /** Entry price */
  entry_price: number;

  /** Exit price */
  exit_price: number;

  /** Realized P&L in currency */
  pnl: number;

  /** Realized P&L percentage */
  pnl_percent: number;

  /** Trade entry timestamp (ISO 8601) */
  opened_at: string;

  /** Trade exit timestamp (ISO 8601) */
  closed_at: string;

  /** Reason for trade closure */
  close_reason: string;
}

/**
 * Frontend-friendly trade display
 */
export interface BotTrade extends AgentTrade {
  /** Display-friendly profit/loss indicator */
  profitDisplay?: string;

  /** Trade result status for UI */
  result?: 'win' | 'loss';
}

// ============================================================================
// Signals
// ============================================================================

/**
 * Trading signal input for agents
 */
export interface SignalInput {
  /** Trading symbol to apply signal to */
  symbol: string;

  /** Signal action (buy/sell/hold) */
  action: SignalAction;

  /** Confidence level (0-1) */
  confidence: number;

  /** Suggested entry price */
  price: number;

  /** Stop loss level */
  stop_loss?: number;

  /** Take profit level */
  take_profit?: number;

  /** Additional metadata */
  metadata?: Record<string, unknown>;
}

// ============================================================================
// Health & System Status
// ============================================================================

/**
 * Health status of Trading Agents service
 */
export interface TradingAgentsHealthResponse {
  /** Overall service health status */
  status: 'healthy' | 'unhealthy';

  /** Service version */
  version: string;

  /** Number of agents currently running */
  agents_running: number;

  /** Service uptime in seconds */
  uptime_seconds: number;
}

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

/**
 * Request to start a trading agent
 */
export interface StartAgentRequest {
  /** Agent type to start */
  agentType: AgentType;

  /** Initial capital */
  initialEquity: number;

  /** Optional trading symbols */
  symbols?: string[];

  /** Risk per trade percentage */
  riskPerTrade?: number;

  /** Max concurrent positions */
  maxPositions?: number;
}

/**
 * Summary of all trading agents
 */
export interface AgentSummary {
  /** Agent type name */
  name: AgentType;

  /** Current agent status */
  status: AgentStatus;

  /** Current equity */
  equity: number;

  /** Open positions count */
  positions: number;

  /** Today's P&L */
  todayPnl: number;

  /** Win rate (optional, when available) */
  winRate?: number;

  /** Total trades executed (optional, when available) */
  totalTrades?: number;
}

/**
 * Response for position closure operation
 */
export interface ClosePositionResponse {
  /** Whether position was successfully closed */
  closed: boolean;

  /** Trade result from position closure */
  trade?: AgentTrade;
}

/**
 * Response for closing all positions
 */
export interface CloseAllPositionsResponse {
  /** Number of positions closed */
  closed: number;
}

/**
 * Response for signal operations
 */
export interface SignalResponse {
  /** Whether signal was received and processed */
  received: boolean;
}

/**
 * Response for broadcast signal
 */
export interface BroadcastSignalResponse {
  /** Number of agents notified */
  agents_notified: number;
}

// ============================================================================
// UI/Display Types
// ============================================================================

/**
 * Chart data for bot performance visualization
 */
export interface BotEquityChartData {
  /** Timestamp */
  time: string;

  /** Equity value at this point */
  equity: number;

  /** P&L at this point */
  pnl: number;
}

/**
 * Comparison data for multiple agents
 */
export interface BotComparison {
  /** Agent type */
  agent: AgentType;

  /** Current equity */
  equity: number;

  /** Total return percentage */
  totalReturn: number;

  /** Win rate */
  winRate: number;

  /** Sharpe ratio */
  sharpeRatio: number;

  /** Status */
  status: BotStatus;
}

/**
 * Filter options for agent trades history
 */
export interface TradeFilterOptions {
  /** Filter by symbol */
  symbol?: string;

  /** Filter by trade side */
  side?: TradeSide;

  /** Filter by result */
  result?: 'win' | 'loss';

  /** Start date (ISO 8601) */
  startDate?: string;

  /** End date (ISO 8601) */
  endDate?: string;

  /** Number of results to return */
  limit?: number;

  /** Offset for pagination */
  offset?: number;
}

// ============================================================================
// Enums for common values
// ============================================================================

/**
 * Agent type enum for dropdown/selection
 */
export enum AgentTypeEnum {
  ATLAS = 'atlas',
  ORION = 'orion',
  NOVA = 'nova',
}

/**
 * Agent status enum
 */
export enum AgentStatusEnum {
  STOPPED = 'stopped',
  STARTING = 'starting',
  RUNNING = 'running',
  PAUSED = 'paused',
  ERROR = 'error',
}

/**
 * Bot display status enum
 */
export enum BotStatusEnum {
  IDLE = 'idle',
  RUNNING = 'running',
  PAUSED = 'paused',
  STOPPED = 'stopped',
  ERROR = 'error',
  UNAVAILABLE = 'unavailable',
}

/**
 * Trade side enum
 */
export enum TradeSideEnum {
  LONG = 'long',
  SHORT = 'short',
}

/**
 * Signal action enum
 */
export enum SignalActionEnum {
  BUY = 'buy',
  SELL = 'sell',
  HOLD = 'hold',
}

// ============================================================================
// Mapping utilities (for use in components)
// ============================================================================

/**
 * Map internal agent status to user-friendly status
 */
export const statusToDisplayStatus = (status: AgentStatus): BotStatus => {
  switch (status) {
    case 'running':
      return 'running';
    case 'paused':
      return 'paused';
    case 'stopped':
      return 'stopped';
    case 'error':
      return 'error';
    default:
      return 'unavailable';
  }
};

/**
 * Get friendly display name for agent type
 */
export const getAgentDisplayName = (agentType: AgentType): string => {
  switch (agentType) {
    case 'atlas':
      return 'Atlas (Conservative)';
    case 'orion':
      return 'Orion (Balanced)';
    case 'nova':
      return 'Nova (Aggressive)';
    default:
      return agentType;
  }
};

/**
 * Get description for agent type
 */
export const getAgentDescription = (agentType: AgentType): string => {
  switch (agentType) {
    case 'atlas':
      return 'Conservative long-term trading strategy with low risk';
    case 'orion':
      return 'Balanced trading strategy with moderate risk/reward';
    case 'nova':
      return 'Aggressive trading strategy with high risk/reward potential';
    default:
      return 'Trading agent';
  }
};
