import type { AlertConditionDto, AlertNotificationDetailDto, IndicatorDataDto } from '../services/alertApi';
import type {
  BacktestResult,
  ChartIndicators,
  ConditionMatch,
  IndicatorData,
  TradeRecord,
} from '../services/backtestApi';
import { normalizeAlertDateTime } from './alertSignalInference';

function indicatorDtoToChartIndicators(d: IndicatorDataDto): ChartIndicators {
  const anyD = d as Record<string, number | undefined>;
  return {
    ma10: d.ma10,
    ma20: d.ma20,
    ma60: d.ma60,
    macdLine: d.macdLine,
    macdSignal: d.signalLine,
    macdHistogram: d.histogram,
    stochK: d.stochK,
    stochD: d.stochD,
    rsi: d.rsi,
    adx: d.adx,
    plusDi: d.plusDI ?? anyD.plusDi,
    minusDi: d.minusDI ?? anyD.minusDi,
    cci: d.cci,
    trix: d.trix,
    trixSignal: d.trixSignal,
    ichimokuTenkan: anyD.ichimokuTenkan,
    ichimokuKijun: anyD.ichimokuKijun,
  };
}

/** 알림 상세 API 응답 → 투자분석 매수·매도 신호 상세 팝업용 TradeRecord */
export function buildTradeRecordFromAlertDetail(
  detail: AlertNotificationDetailDto,
  tradeType: 'BUY' | 'SELL',
  strategyNameHint?: string
): TradeRecord {
  const candleRaw = (detail as { candleTime?: unknown }).candleTime;
  const indicatorTime = detail.indicatorData?.time;
  const ts =
    normalizeAlertDateTime(indicatorTime) ??
    normalizeAlertDateTime(candleRaw) ??
    normalizeAlertDateTime(detail.triggeredAt) ??
    (detail.triggeredAt as string) ??
    '';

  const o = detail.snapshotOpen ?? detail.currentPrice ?? 0;
  const h = detail.snapshotHigh ?? detail.currentPrice ?? 0;
  const l = detail.snapshotLow ?? detail.currentPrice ?? 0;
  const c = detail.snapshotClose ?? detail.currentPrice ?? 0;
  const v = detail.snapshotVolume ?? detail.volume ?? 0;

  const strategyName =
    strategyNameHint?.trim() ||
    (detail.conditionDescription || '').replace(/^전략:\s*/, '').trim() ||
    undefined;

  const indicators = detail.indicatorData ? indicatorDtoToChartIndicators(detail.indicatorData) : undefined;
  const matchedConditions: ConditionMatch[] | undefined = (detail.satisfiedConditions ?? []).map((cond) =>
    toConditionMatch(cond)
  );

  return {
    timestamp: ts,
    tradeType,
    price: c,
    quantity: 0,
    totalAmount: 0,
    commission: 0,
    balance: 0,
    holdings: 0,
    strategyName,
    open: o,
    high: h,
    low: l,
    close: c,
    volume: v,
    indicators,
    matchedConditions,
  };
}

function toConditionMatch(cond: AlertConditionDto): ConditionMatch {
  const indicator = (cond.indicatorType || '').toUpperCase();
  const condition = (cond.conditionType || '').toUpperCase();
  return {
    conditionType: `${indicator}_${condition}`,
    indicatorName: cond.indicatorType,
    description: cond.description || `${cond.indicatorType} ${cond.conditionType}`,
    targetValue: cond.targetValue,
    secondaryValue: cond.secondaryValue,
    matched: true,
  };
}

function toIndicatorData(row: IndicatorDataDto): IndicatorData {
  return {
    time: row.time ?? '',
    timestamp: row.time ?? '',
    macdLine: row.macdLine,
    signalLine: row.signalLine,
    macdSignal: row.signalLine,
    histogram: row.histogram,
    macdHistogram: row.histogram,
    stochK: row.stochK,
    stochD: row.stochD,
    adx: row.adx,
    plusDI: row.plusDI,
    minusDI: row.minusDI,
    cci: row.cci,
    rsi: row.rsi,
    trix: row.trix,
    trixSignal: row.trixSignal,
    ma10: row.ma10,
    ma20: row.ma20,
    ma60: row.ma60,
    ma120: row.ma120,
    ichimokuTenkan: row.ichimokuTenkan,
    ichimokuKijun: row.ichimokuKijun,
    ichimokuSenkouA: row.ichimokuSenkouA,
    ichimokuSenkouB: row.ichimokuSenkouB,
    ichimokuChikou: row.ichimokuChikou,
    open: row.open,
    high: row.high,
    low: row.low,
    close: row.price,
    volume: row.volume,
  };
}

/** 알림 상세 API 응답 → 투자분석 신호상세 차트용 최소 BacktestResult */
export function buildBacktestResultFromAlertDetail(
  detail: AlertNotificationDetailDto,
  trade: TradeRecord
): BacktestResult | null {
  const indicatorData = (detail.indicatorDataSeries ?? [])
    .map(toIndicatorData)
    .filter((x) => !!x.time);

  if (indicatorData.length === 0) return null;

  const symbol = detail.symbol || 'UNKNOWN';
  const strategyName =
    trade.strategyName || (detail.conditionDescription || '').replace(/^전략:\s*/, '').trim() || 'Alert Strategy';

  return {
    symbol,
    strategyId: -1,
    strategyName,
    strategyType: 'ALERT_CONTEXT',
    initialCapital: 0,
    finalCapital: 0,
    netProfit: 0,
    returnRate: 0,
    totalTrades: 1,
    buyCount: trade.tradeType === 'BUY' ? 1 : 0,
    sellCount: trade.tradeType === 'SELL' ? 1 : 0,
    winningTrades: 0,
    losingTrades: 0,
    winRate: 0,
    maxProfit: 0,
    maxLoss: 0,
    avgProfit: 0,
    avgLoss: 0,
    maxConsecutiveWins: 0,
    maxConsecutiveLosses: 0,
    maxCapital: 0,
    maxDrawdown: 0,
    sharpeRatio: 0,
    totalCommission: 0,
    tradeRecords: [trade],
    performanceHistory: [],
    candleData: [],
    indicatorData,
  };
}
