import { LogicNode, ConditionDSL } from '../../services/strategyDSLApi';

/**
 * 미리 구성된 전략 템플릿
 */
export interface StrategyTemplate {
  id: string;
  category: string; // 'MA', 'BOLLINGER', 'ICHIMOKU', 'CCI', 'RSI' 등
  categoryLabel: string;
  signal: 'buy' | 'sell';
  name: string;
  description: string;
  condition: LogicNode;
}

/**
 * MA 설정 정보 (동적 라벨 생성용)
 */
export interface MASettings {
  maLines: Array<{ period: number; enabled: boolean }>;
}

/**
 * 이동평균 전략 템플릿
 */
const MA_TEMPLATES: StrategyTemplate[] = [
  {
    id: 'ma-buy-golden-cross',
    category: 'MA',
    categoryLabel: '이동평균',
    signal: 'buy',
    name: 'MA10 상향돌파 MA20',
    description: '단기 이동평균(10일)이 장기 이동평균(20일)을 상향 돌파 (골든크로스)',
    condition: {
      id: `node-${Date.now()}-ma-golden`,
      type: 'CONDITION',
      condition: {
        indicatorType: 'MA',
        conditionType: 'CROSS_UP',
        leftField: 'MA10',
        rightField: 'MA20',
      }
    }
  },
  {
    id: 'ma-sell-dead-cross',
    category: 'MA',
    categoryLabel: '이동평균',
    signal: 'sell',
    name: 'MA10 하향돌파 MA20',
    description: '단기 이동평균(10일)이 장기 이동평균(20일)을 하향 돌파 (데드크로스)',
    condition: {
      id: `node-${Date.now()}-ma-dead`,
      type: 'CONDITION',
      condition: {
        indicatorType: 'MA',
        conditionType: 'CROSS_DOWN',
        leftField: 'MA10',
        rightField: 'MA20',
      }
    }
  },
  {
    id: 'ma-sell-dead-cross-5-20',
    category: 'MA',
    categoryLabel: '이동평균',
    signal: 'sell',
    name: 'MA5 하향돌파 MA20',
    description: '초단기 이동평균(5일)이 장기 이동평균(20일)을 하향 돌파 (데드크로스)',
    condition: {
      id: `node-${Date.now()}-ma5-20-dead`,
      type: 'CONDITION',
      condition: {
        indicatorType: 'MA',
        conditionType: 'CROSS_DOWN',
        leftField: 'MA5',
        rightField: 'MA20',
      }
    }
  },
  {
    id: 'ma-buy-golden-cross-5-20',
    category: 'MA',
    categoryLabel: '이동평균',
    signal: 'buy',
    name: 'MA5 상향돌파 MA20',
    description: '초단기 이동평균(5일)이 장기 이동평균(20일)을 상향 돌파',
    condition: {
      id: `node-${Date.now()}-ma5-20`,
      type: 'CONDITION',
      condition: {
        indicatorType: 'MA',
        conditionType: 'CROSS_UP',
        leftField: 'MA5',
        rightField: 'MA20',
      }
    }
  },
  {
    id: 'ma-buy-price-above-ma20',
    category: 'MA',
    categoryLabel: '이동평균',
    signal: 'buy',
    name: '종가 > MA20',
    description: '현재가가 20일 이동평균선 위에 위치',
    condition: {
      id: `node-${Date.now()}-price-ma20`,
      type: 'CONDITION',
      condition: {
        indicatorType: 'MA',
        conditionType: 'GT',
        leftField: 'CLOSE_PRICE',
        rightField: 'MA20',
      }
    }
  },
  {
    id: 'ma-buy-uptrend',
    category: 'MA',
    categoryLabel: '이동평균',
    signal: 'buy',
    name: 'MA10 > MA60 AND MA20 > MA60 (정배열)',
    description: '단기/중기 이동평균이 장기 이동평균 위 (정배열)',
    condition: {
      id: `node-${Date.now()}-ma-uptrend`,
      type: 'AND',
      children: [
        {
          id: `node-${Date.now()}-ma10-60`,
          type: 'CONDITION',
          condition: {
            indicatorType: 'MA',
            conditionType: 'GT',
            leftField: 'MA10',
            rightField: 'MA60',
          }
        },
        {
          id: `node-${Date.now()}-ma20-60`,
          type: 'CONDITION',
          condition: {
            indicatorType: 'MA',
            conditionType: 'GT',
            leftField: 'MA20',
            rightField: 'MA60',
          }
        },
      ]
    }
  },
  {
    id: 'ma-sell-downtrend',
    category: 'MA',
    categoryLabel: '이동평균',
    signal: 'sell',
    name: 'MA10 < MA60 AND MA20 < MA60 (역배열)',
    description: '단기/중기 이동평균이 장기 이동평균 아래 (역배열)',
    condition: {
      id: `node-${Date.now()}-ma-downtrend`,
      type: 'AND',
      children: [
        {
          id: `node-${Date.now()}-ma10-60-lt`,
          type: 'CONDITION',
          condition: {
            indicatorType: 'MA',
            conditionType: 'LT',
            leftField: 'MA10',
            rightField: 'MA60',
          }
        },
        {
          id: `node-${Date.now()}-ma20-60-lt`,
          type: 'CONDITION',
          condition: {
            indicatorType: 'MA',
            conditionType: 'LT',
            leftField: 'MA20',
            rightField: 'MA60',
          }
        },
      ]
    }
  },
];

/**
 * 볼린저밴드 전략 템플릿
 */
const BOLLINGER_TEMPLATES: StrategyTemplate[] = [
  {
    id: 'bollinger-buy-lower-band',
    category: 'BOLLINGER',
    categoryLabel: '볼린저밴드',
    signal: 'buy',
    name: '종가가 하단밴드 하향돌파',
    description: '주가가 볼린저밴드 하단선을 하향 돌파 (과매도 신호)',
    condition: {
      id: `node-${Date.now()}-bb-lower`,
      type: 'CONDITION',
      condition: {
        indicatorType: 'BOLLINGER',
        conditionType: 'CROSS_DOWN',
        leftField: 'CLOSE_PRICE',
        rightField: 'LOWER_BAND',
      }
    }
  },
  {
    id: 'bollinger-sell-upper-band',
    category: 'BOLLINGER',
    categoryLabel: '볼린저밴드',
    signal: 'sell',
    name: '종가가 상단밴드 상향돌파',
    description: '주가가 볼린저밴드 상단선을 상향 돌파 (과매수 신호)',
    condition: {
      id: `node-${Date.now()}-bb-upper`,
      type: 'CONDITION',
      condition: {
        indicatorType: 'BOLLINGER',
        conditionType: 'CROSS_UP',
        leftField: 'CLOSE_PRICE',
        rightField: 'UPPER_BAND',
      }
    }
  },
  {
    id: 'bollinger-buy-squeeze',
    category: 'BOLLINGER',
    categoryLabel: '볼린저밴드',
    signal: 'buy',
    name: '밴드폭 축소 (변동성 감소)',
    description: '볼린저밴드 폭이 좁아짐 (큰 변동성 전 신호)',
    condition: {
      id: `node-${Date.now()}-bb-squeeze`,
      type: 'CONDITION',
      condition: {
        indicatorType: 'BWI',
        conditionType: 'BELOW',
        leftField: 'BWI_VALUE',
        rightField: 'THRESHOLD_20',
      }
    }
  },
  {
    id: 'bollinger-buy-below-lower',
    category: 'BOLLINGER',
    categoryLabel: '볼린저밴드',
    signal: 'buy',
    name: '종가 < 하단밴드 (과매도)',
    description: '주가가 볼린저밴드 하단선 아래 (과매도 신호)',
    condition: {
      id: `node-${Date.now()}-bb-below-lower`,
      type: 'CONDITION',
      condition: {
        indicatorType: 'BOLLINGER',
        conditionType: 'LT',
        leftField: 'CLOSE_PRICE',
        rightField: 'LOWER_BAND',
      }
    }
  },
  {
    id: 'bollinger-sell-above-upper',
    category: 'BOLLINGER',
    categoryLabel: '볼린저밴드',
    signal: 'sell',
    name: '종가 > 상단밴드 (과매수)',
    description: '주가가 볼린저밴드 상단선 위 (과매수 신호)',
    condition: {
      id: `node-${Date.now()}-bb-above-upper`,
      type: 'CONDITION',
      condition: {
        indicatorType: 'BOLLINGER',
        conditionType: 'GT',
        leftField: 'CLOSE_PRICE',
        rightField: 'UPPER_BAND',
      }
    }
  },
];

/**
 * 일목균형표 전략 템플릿
 */
const ICHIMOKU_TEMPLATES: StrategyTemplate[] = [
  {
    id: 'ichimoku-buy-golden-cross',
    category: 'ICHIMOKU',
    categoryLabel: '일목균형표',
    signal: 'buy',
    name: '전환선 > 기준선 (정배열)',
    description: '전환선이 기준선을 상향 돌파',
    condition: {
      id: `node-${Date.now()}-ich-golden`,
      type: 'CONDITION',
      condition: {
        indicatorType: 'ICHIMOKU',
        conditionType: 'CROSS_UP',
        leftField: 'CONVERSION_LINE',
        rightField: 'BASE_LINE',
      }
    }
  },
  {
    id: 'ichimoku-sell-dead-cross',
    category: 'ICHIMOKU',
    categoryLabel: '일목균형표',
    signal: 'sell',
    name: '전환선 < 기준선 (역배열)',
    description: '전환선이 기준선을 하향 돌파',
    condition: {
      id: `node-${Date.now()}-ich-dead`,
      type: 'CONDITION',
      condition: {
        indicatorType: 'ICHIMOKU',
        conditionType: 'CROSS_DOWN',
        leftField: 'CONVERSION_LINE',
        rightField: 'BASE_LINE',
      }
    }
  },
  {
    id: 'ichimoku-buy-above-cloud',
    category: 'ICHIMOKU',
    categoryLabel: '일목균형표',
    signal: 'buy',
    name: '주가 > 구름대 (강세)',
    description: '현재가가 구름대(일목균형표 저항대) 위에 위치',
    condition: {
      id: `node-${Date.now()}-ich-above`,
      type: 'CONDITION',
      condition: {
        indicatorType: 'ICHIMOKU',
        conditionType: 'ABOVE_CLOUD',
      }
    }
  },
  {
    id: 'ichimoku-sell-below-cloud',
    category: 'ICHIMOKU',
    categoryLabel: '일목균형표',
    signal: 'sell',
    name: '주가 < 구름대 (약세)',
    description: '현재가가 구름대(일목균형표 지지대) 아래에 위치',
    condition: {
      id: `node-${Date.now()}-ich-below`,
      type: 'CONDITION',
      condition: {
        indicatorType: 'ICHIMOKU',
        conditionType: 'BELOW_CLOUD',
      }
    }
  },
  {
    id: 'ichimoku-buy-above-cloud-golden',
    category: 'ICHIMOKU',
    categoryLabel: '일목균형표',
    signal: 'buy',
    name: '가격 구름 위 + 전환선 > 기준선',
    description: '가격이 구름 위이고 전환선이 기준선을 상향 돌파',
    condition: {
      id: `node-${Date.now()}-ich-above-golden`,
      type: 'AND',
      children: [
        {
          id: `node-${Date.now()}-ich-above`,
          type: 'CONDITION',
          condition: {
            indicatorType: 'ICHIMOKU',
            conditionType: 'ABOVE_CLOUD',
          }
        },
        {
          id: `node-${Date.now()}-ich-golden`,
          type: 'CONDITION',
          condition: {
            indicatorType: 'ICHIMOKU',
            conditionType: 'CROSS_UP',
            leftField: 'CONVERSION_LINE',
            rightField: 'BASE_LINE',
          }
        },
      ]
    }
  },
  {
    id: 'ichimoku-sell-below-cloud-dead',
    category: 'ICHIMOKU',
    categoryLabel: '일목균형표',
    signal: 'sell',
    name: '가격 구름 아래 + 전환선 < 기준선',
    description: '가격이 구름 아래이고 전환선이 기준선을 하향 돌파',
    condition: {
      id: `node-${Date.now()}-ich-below-dead`,
      type: 'AND',
      children: [
        {
          id: `node-${Date.now()}-ich-below`,
          type: 'CONDITION',
          condition: {
            indicatorType: 'ICHIMOKU',
            conditionType: 'BELOW_CLOUD',
          }
        },
        {
          id: `node-${Date.now()}-ich-dead`,
          type: 'CONDITION',
          condition: {
            indicatorType: 'ICHIMOKU',
            conditionType: 'CROSS_DOWN',
            leftField: 'CONVERSION_LINE',
            rightField: 'BASE_LINE',
          }
        },
      ]
    }
  },
  {
    id: 'ichimoku-buy-cloud-break-up',
    category: 'ICHIMOKU',
    categoryLabel: '일목균형표',
    signal: 'buy',
    name: '구름 상향 돌파',
    description: '가격이 구름대를 상향 돌파',
    condition: {
      id: `node-${Date.now()}-ich-cloud-up`,
      type: 'CONDITION',
      condition: {
        indicatorType: 'ICHIMOKU',
        conditionType: 'CLOUD_BREAK_UP',
      }
    }
  },
  {
    id: 'ichimoku-sell-cloud-break-down',
    category: 'ICHIMOKU',
    categoryLabel: '일목균형표',
    signal: 'sell',
    name: '구름 하향 돌파',
    description: '가격이 구름대를 하향 돌파',
    condition: {
      id: `node-${Date.now()}-ich-cloud-down`,
      type: 'CONDITION',
      condition: {
        indicatorType: 'ICHIMOKU',
        conditionType: 'CLOUD_BREAK_DOWN',
      }
    }
  },
];

/**
 * CCI 전략 템플릿
 */
const CCI_TEMPLATES: StrategyTemplate[] = [
  {
    id: 'cci-buy-oversold',
    category: 'CCI',
    categoryLabel: 'CCI',
    signal: 'buy',
    name: 'CCI < -100 (과매도)',
    description: 'CCI 지표가 -100 이하로 하락 (과매도 구간 진입)',
    condition: {
      id: `node-${Date.now()}-cci-oversold`,
      type: 'CONDITION',
      condition: {
        indicatorType: 'CCI',
        conditionType: 'CROSS_DOWN',
        leftField: 'CCI_VALUE',
        rightField: 'OVERSOLD_NEG100',
      }
    }
  },
  {
    id: 'cci-sell-overbought',
    category: 'CCI',
    categoryLabel: 'CCI',
    signal: 'sell',
    name: 'CCI > +100 (과매수)',
    description: 'CCI 지표가 +100 이상으로 상승 (과매수 구간 진입)',
    condition: {
      id: `node-${Date.now()}-cci-overbought`,
      type: 'CONDITION',
      condition: {
        indicatorType: 'CCI',
        conditionType: 'CROSS_UP',
        leftField: 'CCI_VALUE',
        rightField: 'OVERBOUGHT_100',
      }
    }
  },
  {
    id: 'cci-buy-neutral-cross-up',
    category: 'CCI',
    categoryLabel: 'CCI',
    signal: 'buy',
    name: 'CCI 0선 상향돌파',
    description: 'CCI가 0선을 상향 돌파 (상승 전환)',
    condition: {
      id: `node-${Date.now()}-cci-zero-up`,
      type: 'CONDITION',
      condition: {
        indicatorType: 'CCI',
        conditionType: 'CROSS_UP',
        leftField: 'CCI_VALUE',
        rightField: 'NEUTRAL_0',
      }
    }
  },
  {
    id: 'cci-buy-cross-up-oversold',
    category: 'CCI',
    categoryLabel: 'CCI',
    signal: 'buy',
    name: 'CCI 상향돌파 -100',
    description: 'CCI가 -100선을 상향 돌파 (과매도 탈출)',
    condition: {
      id: `node-${Date.now()}-cci-cross-up-100`,
      type: 'CONDITION',
      condition: {
        indicatorType: 'CCI',
        conditionType: 'CROSS_UP',
        leftField: 'CCI_VALUE',
        rightField: 'OVERSOLD_NEG100',
      }
    }
  },
  {
    id: 'cci-sell-cross-down-overbought',
    category: 'CCI',
    categoryLabel: 'CCI',
    signal: 'sell',
    name: 'CCI 하향돌파 100',
    description: 'CCI가 +100선을 하향 돌파 (과매수 탈출)',
    condition: {
      id: `node-${Date.now()}-cci-cross-down-100`,
      type: 'CONDITION',
      condition: {
        indicatorType: 'CCI',
        conditionType: 'CROSS_DOWN',
        leftField: 'CCI_VALUE',
        rightField: 'OVERBOUGHT_100',
      }
    }
  },
];

/**
 * RSI 전략 템플릿
 */
const RSI_TEMPLATES: StrategyTemplate[] = [
  {
    id: 'rsi-buy-oversold',
    category: 'RSI',
    categoryLabel: 'RSI',
    signal: 'buy',
    name: 'RSI < 30 (과매도)',
    description: 'RSI 지표가 30 이하로 하락 (과매도 구간)',
    condition: {
      id: `node-${Date.now()}-rsi-oversold`,
      type: 'CONDITION',
      condition: {
        indicatorType: 'RSI',
        conditionType: 'CROSS_DOWN',
        leftField: 'RSI_VALUE',
        rightField: 'OVERSOLD_30',
      }
    }
  },
  {
    id: 'rsi-sell-overbought',
    category: 'RSI',
    categoryLabel: 'RSI',
    signal: 'sell',
    name: 'RSI > 70 (과매수)',
    description: 'RSI 지표가 70 이상으로 상승 (과매수 구간)',
    condition: {
      id: `node-${Date.now()}-rsi-overbought`,
      type: 'CONDITION',
      condition: {
        indicatorType: 'RSI',
        conditionType: 'CROSS_UP',
        leftField: 'RSI_VALUE',
        rightField: 'OVERBOUGHT_70',
      }
    }
  },
  {
    id: 'rsi-buy-neutral-cross-up',
    category: 'RSI',
    categoryLabel: 'RSI',
    signal: 'buy',
    name: 'RSI 50선 상향돌파',
    description: 'RSI가 50선을 상향 돌파 (상승 추세 전환)',
    condition: {
      id: `node-${Date.now()}-rsi-neutral`,
      type: 'CONDITION',
      condition: {
        indicatorType: 'RSI',
        conditionType: 'CROSS_UP',
        leftField: 'RSI_VALUE',
        rightField: 'NEUTRAL_50',
      }
    }
  },
];

/**
 * Stochastic 전략 템플릿
 */
const STOCHASTIC_TEMPLATES: StrategyTemplate[] = [
  {
    id: 'stoch-buy-oversold',
    category: 'STOCHASTIC',
    categoryLabel: 'Stochastic',
    signal: 'buy',
    name: '%K < 20 (과매도)',
    description: 'Stochastic %K가 20 이하 (과매도 구간)',
    condition: {
      id: `node-${Date.now()}-stoch-oversold`,
      type: 'CONDITION',
      condition: {
        indicatorType: 'STOCHASTIC',
        conditionType: 'BELOW',
        leftField: 'STOCH_K',
        rightField: 'OVERSOLD_20',
      }
    }
  },
  {
    id: 'stoch-sell-overbought',
    category: 'STOCHASTIC',
    categoryLabel: 'Stochastic',
    signal: 'sell',
    name: '%K > 80 (과매수)',
    description: 'Stochastic %K가 80 이상 (과매수 구간)',
    condition: {
      id: `node-${Date.now()}-stoch-overbought`,
      type: 'CONDITION',
      condition: {
        indicatorType: 'STOCHASTIC',
        conditionType: 'ABOVE',
        leftField: 'STOCH_K',
        rightField: 'OVERBOUGHT_80',
      }
    }
  },
  {
    id: 'stoch-buy-golden-cross',
    category: 'STOCHASTIC',
    categoryLabel: 'Stochastic',
    signal: 'buy',
    name: '%K 상향돌파 %D',
    description: 'Stochastic %K가 %D를 상향 돌파',
    condition: {
      id: `node-${Date.now()}-stoch-golden`,
      type: 'CONDITION',
      condition: {
        indicatorType: 'STOCHASTIC',
        conditionType: 'CROSS_UP',
        leftField: 'STOCH_K',
        rightField: 'STOCH_D',
      }
    }
  },
  {
    id: 'stoch-sell-dead-cross',
    category: 'STOCHASTIC',
    categoryLabel: 'Stochastic',
    signal: 'sell',
    name: '%K 하향돌파 %D',
    description: 'Stochastic %K가 %D를 하향 돌파 (데드크로스)',
    condition: {
      id: `node-${Date.now()}-stoch-dead`,
      type: 'CONDITION',
      condition: {
        indicatorType: 'STOCHASTIC',
        conditionType: 'CROSS_DOWN',
        leftField: 'STOCH_K',
        rightField: 'STOCH_D',
      }
    }
  },
];

/**
 * MACD 전략 템플릿
 */
const MACD_TEMPLATES: StrategyTemplate[] = [
  {
    id: 'macd-buy-golden-cross',
    category: 'MACD',
    categoryLabel: 'MACD',
    signal: 'buy',
    name: 'MACD선 상향돌파 Signal선',
    description: 'MACD 라인이 Signal 라인을 상향 돌파 (골든크로스)',
    condition: {
      id: `node-${Date.now()}-macd-golden`,
      type: 'CONDITION',
      condition: {
        indicatorType: 'MACD',
        conditionType: 'CROSS_UP',
        leftField: 'MACD_LINE',
        rightField: 'SIGNAL_LINE',
      }
    }
  },
  {
    id: 'macd-sell-dead-cross',
    category: 'MACD',
    categoryLabel: 'MACD',
    signal: 'sell',
    name: 'MACD선 하향돌파 Signal선',
    description: 'MACD 라인이 Signal 라인을 하향 돌파 (데드크로스)',
    condition: {
      id: `node-${Date.now()}-macd-dead`,
      type: 'CONDITION',
      condition: {
        indicatorType: 'MACD',
        conditionType: 'CROSS_DOWN',
        leftField: 'MACD_LINE',
        rightField: 'SIGNAL_LINE',
      }
    }
  },
  {
    id: 'macd-buy-zero-cross-up',
    category: 'MACD',
    categoryLabel: 'MACD',
    signal: 'buy',
    name: 'MACD 0선 상향돌파',
    description: 'MACD가 0선을 상향 돌파 (상승 추세 전환)',
    condition: {
      id: `node-${Date.now()}-macd-zero`,
      type: 'CONDITION',
      condition: {
        indicatorType: 'MACD',
        conditionType: 'ZERO_CROSS_UP',
      }
    }
  },
];

/**
 * ADX 전략 템플릿
 */
const ADX_TEMPLATES: StrategyTemplate[] = [
  {
    id: 'adx-buy-strong-trend',
    category: 'ADX',
    categoryLabel: 'ADX',
    signal: 'buy',
    name: 'ADX > 25 (강한 추세)',
    description: 'ADX가 25 이상일 때 강한 추세 진입',
    condition: {
      id: `node-${Date.now()}-adx-strong`,
      type: 'CONDITION',
      condition: {
        indicatorType: 'ADX',
        conditionType: 'CROSS_UP',
        leftField: 'ADX_VALUE',
        rightField: 'THRESHOLD_25',
      }
    }
  },
  {
    id: 'adx-sell-weak-trend',
    category: 'ADX',
    categoryLabel: 'ADX',
    signal: 'sell',
    name: 'ADX < 20 (약한 추세)',
    description: 'ADX가 20 이하로 하락 (추세 약화)',
    condition: {
      id: `node-${Date.now()}-adx-weak`,
      type: 'CONDITION',
      condition: {
        indicatorType: 'ADX',
        conditionType: 'CROSS_DOWN',
        leftField: 'ADX_VALUE',
        rightField: 'THRESHOLD_20',
      }
    }
  },
];

/**
 * TRIX 전략 템플릿
 */
const TRIX_TEMPLATES: StrategyTemplate[] = [
  {
    id: 'trix-buy-golden-cross',
    category: 'TRIX',
    categoryLabel: 'TRIX',
    signal: 'buy',
    name: 'TRIX 상향돌파 Signal',
    description: 'TRIX가 Signal선을 상향 돌파 (골든크로스)',
    condition: {
      id: `node-${Date.now()}-trix-golden`,
      type: 'CONDITION',
      condition: {
        indicatorType: 'TRIX',
        conditionType: 'CROSS_UP',
        leftField: 'TRIX_LINE',
        rightField: 'TRIX_SIGNAL',
      }
    }
  },
  {
    id: 'trix-sell-dead-cross',
    category: 'TRIX',
    categoryLabel: 'TRIX',
    signal: 'sell',
    name: 'TRIX 하향돌파 Signal',
    description: 'TRIX가 Signal선을 하향 돌파 (데드크로스)',
    condition: {
      id: `node-${Date.now()}-trix-dead`,
      type: 'CONDITION',
      condition: {
        indicatorType: 'TRIX',
        conditionType: 'CROSS_DOWN',
        leftField: 'TRIX_LINE',
        rightField: 'TRIX_SIGNAL',
      }
    }
  },
  {
    id: 'trix-buy-zero-cross',
    category: 'TRIX',
    categoryLabel: 'TRIX',
    signal: 'buy',
    name: 'TRIX 0선 상향돌파',
    description: 'TRIX가 0선을 상향 돌파 (상승 추세 전환)',
    condition: {
      id: `node-${Date.now()}-trix-zero`,
      type: 'CONDITION',
      condition: {
        indicatorType: 'TRIX',
        conditionType: 'ZERO_CROSS_UP',
      }
    }
  },
];

/**
 * DMI 전략 템플릿
 */
const DMI_TEMPLATES: StrategyTemplate[] = [
  {
    id: 'dmi-buy-plus-cross',
    category: 'DMI',
    categoryLabel: 'DMI',
    signal: 'buy',
    name: '+DI > -DI (상승 우세)',
    description: '+DI가 -DI를 상향 돌파 (상승 추세)',
    condition: {
      id: `node-${Date.now()}-dmi-plus`,
      type: 'CONDITION',
      condition: {
        indicatorType: 'DMI',
        conditionType: 'CROSS_UP',
        leftField: 'PLUS_DI',
        rightField: 'MINUS_DI',
      }
    }
  },
  {
    id: 'dmi-sell-minus-cross',
    category: 'DMI',
    categoryLabel: 'DMI',
    signal: 'sell',
    name: '-DI > +DI (하락 우세)',
    description: '-DI가 +DI를 상향 돌파 (하락 추세)',
    condition: {
      id: `node-${Date.now()}-dmi-minus`,
      type: 'CONDITION',
      condition: {
        indicatorType: 'DMI',
        conditionType: 'CROSS_UP',
        leftField: 'MINUS_DI',
        rightField: 'PLUS_DI',
      }
    }
  },
];

/**
 * OBV 전략 템플릿
 */
const OBV_TEMPLATES: StrategyTemplate[] = [
  {
    id: 'obv-buy-uptrend',
    category: 'OBV',
    categoryLabel: 'OBV',
    signal: 'buy',
    name: 'OBV 상승 (거래량 증가)',
    description: 'OBV가 상승 추세 (매수세 강화)',
    condition: {
      id: `node-${Date.now()}-obv-up`,
      type: 'CONDITION',
      condition: {
        indicatorType: 'OBV',
        conditionType: 'SLOPE_UP',
        leftField: 'OBV_VALUE',
        slopePeriod: 5,
      }
    }
  },
  {
    id: 'obv-sell-downtrend',
    category: 'OBV',
    categoryLabel: 'OBV',
    signal: 'sell',
    name: 'OBV 하락 (거래량 감소)',
    description: 'OBV가 하락 추세 (매도세 강화)',
    condition: {
      id: `node-${Date.now()}-obv-down`,
      type: 'CONDITION',
      condition: {
        indicatorType: 'OBV',
        conditionType: 'SLOPE_DOWN',
        leftField: 'OBV_VALUE',
        slopePeriod: 5,
      }
    }
  },
];

/**
 * VOLUME 전략 템플릿
 */
const VOLUME_TEMPLATES: StrategyTemplate[] = [
  {
    id: 'volume-buy-surge',
    category: 'VOLUME',
    categoryLabel: '거래량',
    signal: 'buy',
    name: '거래량 급증 (평균 2배)',
    description: '거래량이 평균 거래량의 2배 이상',
    condition: {
      id: `node-${Date.now()}-vol-surge`,
      type: 'CONDITION',
      condition: {
        indicatorType: 'VOLUME',
        conditionType: 'DIFF_GT',
        leftField: 'VOLUME_CURRENT',
        rightField: 'VOLUME_AVG',
        compareValue: 2.0,
      }
    }
  },
  {
    id: 'volume-sell-low',
    category: 'VOLUME',
    categoryLabel: '거래량',
    signal: 'sell',
    name: '거래량 감소 (평균 50% 이하)',
    description: '거래량이 평균 거래량의 50% 이하',
    condition: {
      id: `node-${Date.now()}-vol-low`,
      type: 'CONDITION',
      condition: {
        indicatorType: 'VOLUME',
        conditionType: 'DIFF_LT',
        leftField: 'VOLUME_CURRENT',
        rightField: 'VOLUME_AVG',
        compareValue: 0.5,
      }
    }
  },
];

/**
 * DISPARITY 전략 템플릿
 */
const DISPARITY_TEMPLATES: StrategyTemplate[] = [
  {
    id: 'disparity-buy-oversold',
    category: 'DISPARITY',
    categoryLabel: '이격도',
    signal: 'buy',
    name: '이격도 < 95% (과매도)',
    description: '주가가 이동평균선 대비 5% 이상 하락 (과매도)',
    condition: {
      id: `node-${Date.now()}-disp-oversold`,
      type: 'CONDITION',
      condition: {
        indicatorType: 'DISPARITY',
        conditionType: 'CROSS_DOWN',
        leftField: 'DISPARITY_MID',
        rightField: 'OVERSOLD_95',
      }
    }
  },
  {
    id: 'disparity-sell-overbought',
    category: 'DISPARITY',
    categoryLabel: '이격도',
    signal: 'sell',
    name: '이격도 > 105% (과매수)',
    description: '주가가 이동평균선 대비 5% 이상 상승 (과매수)',
    condition: {
      id: `node-${Date.now()}-disp-overbought`,
      type: 'CONDITION',
      condition: {
        indicatorType: 'DISPARITY',
        conditionType: 'CROSS_UP',
        leftField: 'DISPARITY_MID',
        rightField: 'OVERBOUGHT_105',
      }
    }
  },
  {
    id: 'disparity-buy-neutral',
    category: 'DISPARITY',
    categoryLabel: '이격도',
    signal: 'buy',
    name: '이격도 100% 상향돌파',
    description: '주가가 이동평균선으로 회귀 후 상승',
    condition: {
      id: `node-${Date.now()}-disp-neutral`,
      type: 'CONDITION',
      condition: {
        indicatorType: 'DISPARITY',
        conditionType: 'CROSS_UP',
        leftField: 'DISPARITY_MID',
        rightField: 'NEUTRAL_100',
      }
    }
  },
];

/**
 * NEW_PSYCHOLOGICAL 전략 템플릿
 */
const NEW_PSYCHOLOGICAL_TEMPLATES: StrategyTemplate[] = [
  {
    id: 'new-psy-buy-oversold',
    category: 'NEW_PSYCHOLOGICAL',
    categoryLabel: '신심리도',
    signal: 'buy',
    name: '신심리도 < 25% (과매도)',
    description: '신심리도가 25% 이하 (과도한 비관)',
    condition: {
      id: `node-${Date.now()}-npsy-oversold`,
      type: 'CONDITION',
      condition: {
        indicatorType: 'NEW_PSYCHOLOGICAL',
        conditionType: 'CROSS_DOWN',
        leftField: 'NEW_PSY_VALUE',
        rightField: 'OVERSOLD_25',
      }
    }
  },
  {
    id: 'new-psy-sell-overbought',
    category: 'NEW_PSYCHOLOGICAL',
    categoryLabel: '신심리도',
    signal: 'sell',
    name: '신심리도 > 75% (과매수)',
    description: '신심리도가 75% 이상 (과도한 낙관)',
    condition: {
      id: `node-${Date.now()}-npsy-overbought`,
      type: 'CONDITION',
      condition: {
        indicatorType: 'NEW_PSYCHOLOGICAL',
        conditionType: 'CROSS_UP',
        leftField: 'NEW_PSY_VALUE',
        rightField: 'OVERBOUGHT_75',
      }
    }
  },
];

/**
 * INVEST_PSYCHOLOGICAL 전략 템플릿
 */
const INVEST_PSYCHOLOGICAL_TEMPLATES: StrategyTemplate[] = [
  {
    id: 'invest-psy-buy-oversold',
    category: 'INVEST_PSYCHOLOGICAL',
    categoryLabel: '투자심리도',
    signal: 'buy',
    name: '투자심리도 < 25% (과매도)',
    description: '투자심리도가 25% 이하 (공포 구간)',
    condition: {
      id: `node-${Date.now()}-ipsy-oversold`,
      type: 'CONDITION',
      condition: {
        indicatorType: 'INVEST_PSYCHOLOGICAL',
        conditionType: 'CROSS_DOWN',
        leftField: 'INVEST_PSY_VALUE',
        rightField: 'OVERSOLD_25',
      }
    }
  },
  {
    id: 'invest-psy-sell-overbought',
    category: 'INVEST_PSYCHOLOGICAL',
    categoryLabel: '투자심리도',
    signal: 'sell',
    name: '투자심리도 > 75% (과매수)',
    description: '투자심리도가 75% 이상 (탐욕 구간)',
    condition: {
      id: `node-${Date.now()}-ipsy-overbought`,
      type: 'CONDITION',
      condition: {
        indicatorType: 'INVEST_PSYCHOLOGICAL',
        conditionType: 'CROSS_UP',
        leftField: 'INVEST_PSY_VALUE',
        rightField: 'OVERBOUGHT_75',
      }
    }
  },
];

/**
 * WILLIAMS_R 전략 템플릿
 */
const WILLIAMS_R_TEMPLATES: StrategyTemplate[] = [
  {
    id: 'williams-buy-oversold',
    category: 'WILLIAMS_R',
    categoryLabel: 'Williams %R',
    signal: 'buy',
    name: 'Williams %R < -80 (과매도)',
    description: 'Williams %R이 -80 이하 (과매도 구간)',
    condition: {
      id: `node-${Date.now()}-wr-oversold`,
      type: 'CONDITION',
      condition: {
        indicatorType: 'WILLIAMS_R',
        conditionType: 'CROSS_DOWN',
        leftField: 'WILLIAMS_R_VALUE',
        rightField: 'OVERSOLD_NEG80',
      }
    }
  },
  {
    id: 'williams-sell-overbought',
    category: 'WILLIAMS_R',
    categoryLabel: 'Williams %R',
    signal: 'sell',
    name: 'Williams %R > -20 (과매수)',
    description: 'Williams %R이 -20 이상 (과매수 구간)',
    condition: {
      id: `node-${Date.now()}-wr-overbought`,
      type: 'CONDITION',
      condition: {
        indicatorType: 'WILLIAMS_R',
        conditionType: 'CROSS_UP',
        leftField: 'WILLIAMS_R_VALUE',
        rightField: 'OVERBOUGHT_NEG20',
      }
    }
  },
];

/**
 * BWI 전략 템플릿
 */
const BWI_TEMPLATES: StrategyTemplate[] = [
  {
    id: 'bwi-buy-squeeze',
    category: 'BWI',
    categoryLabel: 'BWI',
    signal: 'buy',
    name: 'BWI < 20% (밴드폭 축소)',
    description: '볼린저밴드 폭이 축소 (변동성 감소, 큰 움직임 전조)',
    condition: {
      id: `node-${Date.now()}-bwi-squeeze`,
      type: 'CONDITION',
      condition: {
        indicatorType: 'BWI',
        conditionType: 'BELOW',
        leftField: 'BWI_VALUE',
        rightField: 'THRESHOLD_20',
      }
    }
  },
  {
    id: 'bwi-sell-expansion',
    category: 'BWI',
    categoryLabel: 'BWI',
    signal: 'sell',
    name: 'BWI > 80% (밴드폭 확대)',
    description: '볼린저밴드 폭이 확대 (고점 근처, 변동성 최고조)',
    condition: {
      id: `node-${Date.now()}-bwi-expand`,
      type: 'CONDITION',
      condition: {
        indicatorType: 'BWI',
        conditionType: 'ABOVE',
        leftField: 'BWI_VALUE',
        rightField: 'THRESHOLD_80',
      }
    }
  },
];

/**
 * VR 전략 템플릿
 */
const VR_TEMPLATES: StrategyTemplate[] = [
  {
    id: 'vr-buy-oversold',
    category: 'VR',
    categoryLabel: 'VR',
    signal: 'buy',
    name: 'VR < 70% (과매도)',
    description: 'VR이 70% 이하 (거래량 부족, 반등 가능)',
    condition: {
      id: `node-${Date.now()}-vr-oversold`,
      type: 'CONDITION',
      condition: {
        indicatorType: 'VR',
        conditionType: 'CROSS_DOWN',
        leftField: 'VR_VALUE',
        rightField: 'OVERSOLD_70',
      }
    }
  },
  {
    id: 'vr-sell-overbought',
    category: 'VR',
    categoryLabel: 'VR',
    signal: 'sell',
    name: 'VR > 150% (과매수)',
    description: 'VR이 150% 이상 (거래량 과열)',
    condition: {
      id: `node-${Date.now()}-vr-overbought`,
      type: 'CONDITION',
      condition: {
        indicatorType: 'VR',
        conditionType: 'CROSS_UP',
        leftField: 'VR_VALUE',
        rightField: 'OVERBOUGHT_150',
      }
    }
  },
  {
    id: 'vr-buy-neutral-cross',
    category: 'VR',
    categoryLabel: 'VR',
    signal: 'buy',
    name: 'VR 100% 상향돌파',
    description: 'VR이 100%를 상향 돌파 (거래량 증가)',
    condition: {
      id: `node-${Date.now()}-vr-neutral`,
      type: 'CONDITION',
      condition: {
        indicatorType: 'VR',
        conditionType: 'CROSS_UP',
        leftField: 'VR_VALUE',
        rightField: 'NEUTRAL_100',
      }
    }
  },
];

/**
 * VOLUME_OSC 전략 템플릿
 */
const VOLUME_OSC_TEMPLATES: StrategyTemplate[] = [
  {
    id: 'volosc-buy-positive',
    category: 'VOLUME_OSC',
    categoryLabel: 'Volume OSC',
    signal: 'buy',
    name: 'Volume OSC > 0 (거래량 증가)',
    description: 'Volume Oscillator가 0선 상향 돌파',
    condition: {
      id: `node-${Date.now()}-volosc-pos`,
      type: 'CONDITION',
      condition: {
        indicatorType: 'VOLUME_OSC',
        conditionType: 'ZERO_CROSS_UP',
      }
    }
  },
  {
    id: 'volosc-sell-negative',
    category: 'VOLUME_OSC',
    categoryLabel: 'Volume OSC',
    signal: 'sell',
    name: 'Volume OSC < 0 (거래량 감소)',
    description: 'Volume Oscillator가 0선 하향 돌파',
    condition: {
      id: `node-${Date.now()}-volosc-neg`,
      type: 'CONDITION',
      condition: {
        indicatorType: 'VOLUME_OSC',
        conditionType: 'ZERO_CROSS_DOWN',
      }
    }
  },
];

/**
 * 전체 템플릿 그룹 정의
 */
export interface TemplateCategory {
  id: string;
  label: string;
  icon: string;
  templates: StrategyTemplate[];
}

export const TEMPLATE_CATEGORIES: TemplateCategory[] = [
  {
    id: 'MA',
    label: '이동평균',
    icon: '📈',
    templates: MA_TEMPLATES,
  },
  {
    id: 'BOLLINGER',
    label: '볼린저밴드',
    icon: '📉',
    templates: BOLLINGER_TEMPLATES,
  },
  {
    id: 'ICHIMOKU',
    label: '일목균형표',
    icon: '☁️',
    templates: ICHIMOKU_TEMPLATES,
  },
  {
    id: 'MACD',
    label: 'MACD',
    icon: '📊',
    templates: MACD_TEMPLATES,
  },
  {
    id: 'RSI',
    label: 'RSI',
    icon: '📉',
    templates: RSI_TEMPLATES,
  },
  {
    id: 'STOCHASTIC',
    label: 'Stochastic',
    icon: '📊',
    templates: STOCHASTIC_TEMPLATES,
  },
  {
    id: 'CCI',
    label: 'CCI',
    icon: '📈',
    templates: CCI_TEMPLATES,
  },
  {
    id: 'ADX',
    label: 'ADX',
    icon: '📊',
    templates: ADX_TEMPLATES,
  },
  {
    id: 'TRIX',
    label: 'TRIX',
    icon: '📉',
    templates: TRIX_TEMPLATES,
  },
  {
    id: 'DMI',
    label: 'DMI',
    icon: '📊',
    templates: DMI_TEMPLATES,
  },
  {
    id: 'OBV',
    label: 'OBV',
    icon: '📈',
    templates: OBV_TEMPLATES,
  },
  {
    id: 'VOLUME',
    label: '거래량',
    icon: '📊',
    templates: VOLUME_TEMPLATES,
  },
  {
    id: 'DISPARITY',
    label: '이격도',
    icon: '📉',
    templates: DISPARITY_TEMPLATES,
  },
  {
    id: 'NEW_PSYCHOLOGICAL',
    label: '신심리도',
    icon: '🧠',
    templates: NEW_PSYCHOLOGICAL_TEMPLATES,
  },
  {
    id: 'INVEST_PSYCHOLOGICAL',
    label: '투자심리도',
    icon: '💭',
    templates: INVEST_PSYCHOLOGICAL_TEMPLATES,
  },
  {
    id: 'WILLIAMS_R',
    label: 'Williams %R',
    icon: '📊',
    templates: WILLIAMS_R_TEMPLATES,
  },
  {
    id: 'BWI',
    label: 'BWI',
    icon: '📏',
    templates: BWI_TEMPLATES,
  },
  {
    id: 'VR',
    label: 'VR',
    icon: '📊',
    templates: VR_TEMPLATES,
  },
  {
    id: 'VOLUME_OSC',
    label: 'Volume OSC',
    icon: '📊',
    templates: VOLUME_OSC_TEMPLATES,
  },
];

/**
 * 사용자 정의 템플릿 관리
 */
const CUSTOM_TEMPLATES_KEY = 'strategy_custom_templates';

/**
 * 로컬 스토리지에서 사용자 정의 템플릿 로드
 */
export const loadCustomTemplates = (): StrategyTemplate[] => {
  try {
    const stored = localStorage.getItem(CUSTOM_TEMPLATES_KEY);
    if (!stored) return [];
    return JSON.parse(stored) as StrategyTemplate[];
  } catch (error) {
    console.error('사용자 정의 템플릿 로드 실패:', error);
    return [];
  }
};

/**
 * 사용자 정의 템플릿 저장
 */
export const saveCustomTemplate = (template: StrategyTemplate): boolean => {
  try {
    const customTemplates = loadCustomTemplates();
    const existingIndex = customTemplates.findIndex(t => t.id === template.id);
    
    if (existingIndex >= 0) {
      // 기존 템플릿 업데이트
      customTemplates[existingIndex] = template;
      console.log('✅ 템플릿 업데이트:', template.name);
    } else {
      // 새 템플릿 추가
      customTemplates.push(template);
      console.log('✅ 새 템플릿 추가:', template.name);
    }
    
    localStorage.setItem(CUSTOM_TEMPLATES_KEY, JSON.stringify(customTemplates));
    return true;
  } catch (error) {
    console.error('❌ 템플릿 저장 실패:', error);
    return false;
  }
};

/**
 * 템플릿 이름으로 검색
 */
export const findTemplateByName = (name: string): StrategyTemplate | null => {
  // 기본 템플릿 검색
  for (const category of TEMPLATE_CATEGORIES) {
    const found = category.templates.find(t => t.name === name);
    if (found) return found;
  }
  
  // 사용자 정의 템플릿 검색
  const customTemplates = loadCustomTemplates();
  return customTemplates.find(t => t.name === name) || null;
};

/**
 * 템플릿 ID로 검색
 */
export const findTemplateById = (id: string): StrategyTemplate | null => {
  // 기본 템플릿 검색
  for (const category of TEMPLATE_CATEGORIES) {
    const found = category.templates.find(t => t.id === id);
    if (found) return found;
  }
  
  // 사용자 정의 템플릿 검색
  const customTemplates = loadCustomTemplates();
  return customTemplates.find(t => t.id === id) || null;
};

/**
 * 사용자 정의 템플릿 삭제
 */
export const deleteCustomTemplate = (id: string): boolean => {
  try {
    const customTemplates = loadCustomTemplates();
    const filtered = customTemplates.filter(t => t.id !== id);
    localStorage.setItem(CUSTOM_TEMPLATES_KEY, JSON.stringify(filtered));
    console.log('✅ 템플릿 삭제:', id);
    return true;
  } catch (error) {
    console.error('❌ 템플릿 삭제 실패:', error);
    return false;
  }
};

/**
 * MA 필드를 동적 라벨로 변환
 * @param field 'MA5', 'MA10', 'MA20' 등
 * @param maSettings 현재 MA 설정
 * @returns 'MA1(5일)', 'MA2(10일)' 등
 */
const convertMAFieldToLabel = (field: string | undefined, maSettings: MASettings): string => {
  if (!field) return '';
  if (field === 'CLOSE_PRICE') return '종가';
  if (field === 'NONE') return '';
  
  // MA5, MA10, MA20 등 파싱
  const match = field.match(/^MA(\d+)$/);
  if (!match) return field;
  
  const period = parseInt(match[1]);
  const enabledMAs = maSettings.maLines.filter(ma => ma.enabled);
  const allMAs = maSettings.maLines;
  
  // 1단계: enabled된 MA 중에서 찾기
  let maIndex = enabledMAs.findIndex(ma => ma.period === period);
  if (maIndex >= 0) {
    return `MA${maIndex + 1}(${period}일)`;
  }
  
  // 2단계: 전체 MA 목록에서 찾기 (disabled 포함)
  const allIndex = allMAs.findIndex(ma => ma.period === period);
  if (allIndex >= 0) {
    return `MA${allIndex + 1}(${period}일)`;
  }
  
  // 3단계: 가장 가까운 enabled MA 찾기
  if (enabledMAs.length > 0) {
    const closest = enabledMAs.reduce((prev, curr) => {
      return Math.abs(curr.period - period) < Math.abs(prev.period - period) ? curr : prev;
    });
    const closestIndex = enabledMAs.findIndex(ma => ma.period === closest.period);
    return `MA${closestIndex + 1}(${closest.period}일)`;
  }
  
  // 4단계: 못 찾으면 기간만 표시
  return `${period}일`;
};

/**
 * 템플릿 이름을 현재 MA 설정에 맞게 동적으로 생성
 * @param template 템플릿
 * @param maSettings 현재 MA 설정
 * @returns 동적으로 생성된 이름
 */
export const getDynamicTemplateName = (template: StrategyTemplate, maSettings?: MASettings): string => {
  // MA 템플릿이 아니거나 MA 설정이 없으면 원래 이름 반환
  if (template.category !== 'MA' || !maSettings) {
    return template.name;
  }
  
  // 단일 조건 템플릿
  if (template.condition.type === 'CONDITION' && template.condition.condition) {
    const cond = template.condition.condition;
    const leftLabel = convertMAFieldToLabel(cond.leftField, maSettings);
    const rightLabel = convertMAFieldToLabel(cond.rightField, maSettings);
    
    const conditionLabel = cond.conditionType === 'CROSS_UP' ? '상향돌파' :
                           cond.conditionType === 'CROSS_DOWN' ? '하향돌파' :
                           cond.conditionType === 'GT' ? '>' :
                           cond.conditionType === 'LT' ? '<' :
                           cond.conditionType;
    
    if (rightLabel) {
      return `${leftLabel} ${conditionLabel} ${rightLabel}`;
    }
    return `${leftLabel} ${conditionLabel}`;
  }
  
  // AND 조건 템플릿 (정배열, 역배열 등)
  if ((template.condition.type === 'AND' || template.condition.type === 'OR') && template.condition.children) {
    // 복잡한 조건은 원래 이름 유지 (또는 필요시 개별 처리)
    return template.name;
  }
  
  return template.name;
};

/**
 * 템플릿 설명을 현재 MA 설정에 맞게 동적으로 생성
 */
export const getDynamicTemplateDescription = (template: StrategyTemplate, maSettings?: MASettings): string => {
  if (template.category !== 'MA' || !maSettings) {
    return template.description;
  }
  
  // 설명도 동적으로 생성 가능
  if (template.condition.type === 'CONDITION' && template.condition.condition) {
    const cond = template.condition.condition;
    const leftLabel = convertMAFieldToLabel(cond.leftField, maSettings);
    const rightLabel = convertMAFieldToLabel(cond.rightField, maSettings);
    
    if (cond.conditionType === 'CROSS_UP') {
      return `${leftLabel}이 ${rightLabel}을 상향 돌파`;
    } else if (cond.conditionType === 'CROSS_DOWN') {
      return `${leftLabel}이 ${rightLabel}을 하향 돌파`;
    } else if (cond.conditionType === 'GT') {
      return `${leftLabel}이 ${rightLabel}보다 큼`;
    }
  }
  
  return template.description;
};
