import type { BacktestResult } from './types';

export const toDateInputValue = (timestamp: number): string => {
    const date = new Date(timestamp);
    const year = date.getUTCFullYear();
    const month = String(date.getUTCMonth() + 1).padStart(2, '0');
    const day = String(date.getUTCDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
};

export const parseSymbolsInput = (raw: string): string[] =>
    String(raw || '')
        .split(',')
        .map((value) => value.trim().toUpperCase())
        .filter(Boolean);

export const toEquitySeries = (result: BacktestResult) =>
    (result.timeline || []).map((point) => ({
        timestamp: point.timestamp,
        equityUsd: point.equityUsd,
        drawdownPct: point.drawdownPct
    }));

const topRecord = (record: Record<string, number>): [string, number] | null => {
    const entries = Object.entries(record || {});
    if (!entries.length) return null;
    return entries.sort((a, b) => b[1] - a[1])[0] || null;
};

export const buildInsightCards = (result: BacktestResult): Array<{ title: string; value: string; detail: string }> => {
    const lossTop = topRecord(result?.diagnostics?.lossReasons || {});
    const blockedTop = topRecord(result?.diagnostics?.blockedRuleCounts || {});
    const rejectTop = topRecord(result?.diagnostics?.entryRejections || {});

    return [
        {
            title: 'Why This Strategy Lost Here',
            value: lossTop ? `${lossTop[0]} (${lossTop[1]})` : 'No losing exits',
            detail: 'Most frequent loss-associated exit reason during replay.'
        },
        {
            title: 'Which Rules Blocked Trades',
            value: blockedTop ? `${blockedTop[0]} (${blockedTop[1]})` : 'No blocks recorded',
            detail: 'Top rule failure encountered while evaluating entries.'
        },
        {
            title: 'Entry Rejections',
            value: rejectTop ? `${rejectTop[0]} (${rejectTop[1]})` : 'No rejections',
            detail: 'Most common reason an eligible entry was not executed.'
        }
    ];
};

