import type { CandleData, IndicatorData } from '../../services/backtestApi';
import type { IndicatorSettings } from '../../contexts/IndicatorSettingsContext';

/**
 * 투자분석 `loadIndicatorDataSync`의 `/upbit/analyze` 요청 본문과 동일한 구조.
 * 멀티차트·멀티차트2 ChartItemInvestment에서 사용.
 */
export function buildUpbitAnalyzePayload(params: {
  symbol: string;
  interval: string;
  candleData: CandleData[];
  maPeriods: number[];
  bollingerPeriod: number;
  bollingerStdDev: number;
  settings: IndicatorSettings;
  vrPeriod: number;
  vr2Enabled: boolean;
  vr2Period: number;
}): Record<string, unknown> {
  const s = params.settings;
  return {
    symbol: params.symbol,
    interval: params.interval,
    candleData: params.candleData,
    maPeriods: params.maPeriods,
    cciPeriod: s.cciPeriod || 13,
    cciSignalPeriod: s.cciSignalPeriod || 10,
    adxPeriod: s.adxPeriod || 14,
    dmiPeriod: s.dmiPeriod || 14,
    rsiPeriod: s.rsiPeriod || 9,
    macdFastPeriod: s.macdFastPeriod || 12,
    macdSlowPeriod: s.macdSlowPeriod || 26,
    macdSignalPeriod: s.macdSignalPeriod || 9,
    indicatorSettings: {
      bollingerPeriod: params.bollingerPeriod,
      bollingerStdDev: params.bollingerStdDev,
      maPeriods: params.maPeriods,
      cciPeriod: s.cciPeriod || 13,
      cciSignalPeriod: s.cciSignalPeriod || 10,
      rsiPeriod: s.rsiPeriod || 9,
      rsiSignalPeriod: s.rsiSignalPeriod || 9,
      macdFastPeriod: s.macdFastPeriod || 12,
      macdSlowPeriod: s.macdSlowPeriod || 26,
      macdSignalPeriod: s.macdSignalPeriod || 9,
      stochasticKPeriod: s.stochasticKPeriod || 12,
      stochasticDPeriod: s.stochasticDPeriod || 5,
      stochasticSlowing: s.stochasticSlowing || 5,
      adxPeriod: s.adxPeriod || 14,
      dmiPeriod: s.dmiPeriod || 14,
      obvPeriod: s.obvPeriod || 10,
      obvSignalPeriod: s.obvSignalPeriod || 10,
      williamsRPeriod: s.williamsRPeriod || 14,
      trixPeriod: s.trixPeriod || 12,
      trixSignalPeriod: s.trixSignalPeriod || 9,
      volumeOscShortPeriod: s.volumeOscShortPeriod || 5,
      volumeOscLongPeriod: s.volumeOscLongPeriod || 10,
      disparityUltraShortPeriod: s.disparityUltraShortPeriod || 5,
      disparityShortPeriod: s.disparityShortPeriod || 20,
      disparityMidPeriod: s.disparityMidPeriod || 60,
      disparityLongPeriod: s.disparityLongPeriod || 120,
      newPsychologicalPeriod: s.newPsychologicalPeriod || 12,
      investPsychologicalPeriod: s.investPsychologicalPeriod || 24,
      bwiPeriod: s.bwiPeriod || 20,
    },
    vrPeriod: params.vrPeriod,
    vr2Enabled: params.vr2Enabled,
    vr2Period: params.vr2Period,
  };
}

/** API 행 → CandlestickChart용 IndicatorData 정규화 */
export function normalizeAnalyzeIndicatorRow(d: any): Record<string, unknown> {
  const ts = d.timestamp ?? d.time ?? d.date;
  const timeStr =
    typeof ts === 'number'
      ? new Date(ts >= 1e12 ? ts : ts * 1000).toISOString().slice(0, 19).replace('Z', '')
      : (d.time ?? (ts ? new Date(String(ts)).toISOString().slice(0, 19).replace('Z', '') : ''));
  return {
    ...d,
    time: timeStr,
    timestamp: String(ts ?? ''),
    stochasticK: d.stochasticK ?? d.stochK,
    stochasticD: d.stochasticD ?? d.stochD,
    macdHistogram: d.macdHistogram ?? d.histogram,
    cci: d.cci ?? d.cci13,
    cci13: d.cci13 ?? d.cci,
  };
}

/**
 * /upbit/analyze 행은 요청 candleData 와 인덱스 1:1이다.
 * 백엔드 timestamp 문자열과 프론트 parseCandles 의 time(UTC ISO) 형식이 다르면
 * 서브패널 mapIndicatorData 가 메인 캔들과 다른 unix time 을 만들어 CCI/ADX 등이 직선·깨짐으로 그려질 수 있다.
 * 투자분석과 동일하게 각 행의 time 을 같은 인덱스 캔들 time 으로 고정한다.
 */
export function alignIndicatorRowsToCandleTimes(
  rows: IndicatorData[],
  candles: CandleData[]
): IndicatorData[] {
  const n = Math.min(rows.length, candles.length);
  const out: IndicatorData[] = [];
  for (let i = 0; i < n; i++) {
    const ct = candles[i]?.time;
    const row = rows[i] as IndicatorData;
    out.push({
      ...row,
      time: ct != null && ct !== '' ? ct : row.time,
      timestamp: ct != null && ct !== '' ? String(ct) : row.timestamp,
    });
  }
  return out;
}
