export type TradeSleeve = 'core' | 'idle_alpha' | 'risk_off_alpha' | 'ownership' | 'parking';

export const IDLE_ALPHA_ENGINE_IDS = [
  'next_open_long_material_contract_mixed_micro_postmarket',
  'next_open_long_guidance_mixed_micro_postmarket',
  'next_open_long_earnings_unknown_inline_postmarket_strict',
  'next_open_long_bullish_raised_strong',
  'idle_macro_breadth_smh_postalloc',
  'next_open_long_unknown_event_micro_postmarket',
  'next_open_long_other_material_micro_postmarket',
  'idle_dividend_capture',
] as const;

export const OWNERSHIP_ENGINE_IDS = [
  'idle_ownership_13d_capture',
] as const;

export const RISK_OFF_ALPHA_ENGINE_IDS = [
  'idle_risk_off_alpha',
] as const;

const IDLE_ALPHA_ENGINE_ID_SET = new Set<string>(IDLE_ALPHA_ENGINE_IDS);
const OWNERSHIP_ENGINE_ID_SET = new Set<string>(OWNERSHIP_ENGINE_IDS);
const RISK_OFF_ALPHA_ENGINE_ID_SET = new Set<string>(RISK_OFF_ALPHA_ENGINE_IDS);

export function classifyTradeSleeve(trade: {
  engine_id?: unknown;
  event_type?: unknown;
  exit_reason?: unknown;
  reason?: unknown;
  trade_sleeve?: unknown;
  sleeve?: unknown;
}): TradeSleeve {
  const explicitSleeve = String(trade.trade_sleeve ?? trade.sleeve ?? '').trim().toLowerCase();
  const engineId = String(trade.engine_id ?? '').trim();
  const eventType = String(trade.event_type ?? '').trim();
  const exitReason = String(trade.exit_reason ?? trade.reason ?? '').trim().toUpperCase();

  if (explicitSleeve === 'parking') return 'parking';
  if (explicitSleeve === 'idle_alpha') return 'idle_alpha';
  if (explicitSleeve === 'risk_off_alpha') return 'risk_off_alpha';
  if (explicitSleeve === 'ownership') return 'ownership';
  if (explicitSleeve === 'core') return 'core';
  if (engineId === 'cash_parking' || eventType === 'cash_parking' || exitReason === 'PARKING') {
    return 'parking';
  }
  if (engineId && IDLE_ALPHA_ENGINE_ID_SET.has(engineId)) {
    return 'idle_alpha';
  }
  if (engineId && RISK_OFF_ALPHA_ENGINE_ID_SET.has(engineId)) {
    return 'risk_off_alpha';
  }
  if (engineId && OWNERSHIP_ENGINE_ID_SET.has(engineId)) {
    return 'ownership';
  }
  return 'core';
}

export function tradeSleeveLabel(sleeve: TradeSleeve): string {
  if (sleeve === 'parking') return 'Parking';
  if (sleeve === 'idle_alpha') return 'Idle Alpha';
  if (sleeve === 'risk_off_alpha') return 'Risk-Off Alpha';
  if (sleeve === 'ownership') return 'Ownership';
  return 'Core';
}
