/**
 * 전략 규칙(StrategyRule)의 보조지표 조건 → 차트 보조지표 설정(indicatorSettings) 매핑
 * ChartItem INDICATOR_MENU_ITEMS 키와 대응
 */
import type { StrategyRuleDto, StrategyConditionDto, ConditionGroupDto } from '../services/strategyRuleApi';

/** 전략 규칙 IndicatorType → 차트 indicatorSettings 키 */
const INDICATOR_TYPE_TO_CHART_KEY: Record<string, string> = {
  VOLUME: 'volume',
  MACD: 'macd',
  MACD_SIGNAL: 'macd',
  MACD_HISTOGRAM: 'macd',
  RSI: 'rsi',
  STOCHASTIC: 'stochastic',
  STOCHASTIC_K: 'stochastic',
  STOCHASTIC_D: 'stochastic',
  ADX: 'adx',
  CCI: 'cci',
  OBV: 'obv',
  NEW_PSYCHOLOGICAL: 'newPsychological',
  INVEST_PSYCHOLOGICAL: 'investPsychological',
  BWI: 'bwi',
  WILLIAMS_R: 'williamsR',
  TRIX: 'trix',
  TRIX_SIGNAL: 'trix',
  VOLUME_OSC: 'volumeOsc',
  VR: 'vr',
  DISPARITY: 'disparity',
  DMI: 'dmi',
  PLUS_DI: 'dmi',
  MINUS_DI: 'dmi',
};

/**
 * 전략 규칙에서 보조지표 관련 조건의 indicatorType 추출
 */
function collectIndicatorTypesFromConditions(conditions: StrategyConditionDto[]): Set<string> {
  const types = new Set<string>();
  for (const c of conditions) {
    if (c.indicatorType && c.enabled !== false) {
      const chartKey = INDICATOR_TYPE_TO_CHART_KEY[c.indicatorType];
      if (chartKey) types.add(chartKey);
    }
  }
  return types;
}

function collectFromGroup(group: ConditionGroupDto | undefined): Set<string> {
  const types = new Set<string>();
  if (!group) return types;
  const fromConditions = collectIndicatorTypesFromConditions(group.conditions || []);
  fromConditions.forEach((t) => types.add(t));
  (group.childGroups || []).forEach((cg) => {
    collectFromGroup(cg).forEach((t) => types.add(t));
  });
  return types;
}

/**
 * 전략 규칙 DTO에서 사용된 보조지표 키 목록 추출
 */
export function extractIndicatorKeysFromStrategyRule(rule: StrategyRuleDto): string[] {
  const keys = new Set<string>();
  (rule.buyConditionGroups || []).forEach((g) => collectFromGroup(g).forEach((k) => keys.add(k)));
  (rule.sellConditionGroups || []).forEach((g) => collectFromGroup(g).forEach((k) => keys.add(k)));
  return Array.from(keys);
}

/**
 * indicatorKeys → ChartItem indicatorSettings 형식 (Record<string, boolean>)
 */
export function indicatorKeysToSettings(keys: string[]): Record<string, boolean> {
  const settings: Record<string, boolean> = {};
  for (const k of keys) {
    settings[k] = true;
  }
  return settings;
}
