export interface StrategyExplanation {
    reason: string;
    recommendation?: string;
    severity: 'info' | 'success' | 'warning';
}

export const getStrategyExplanation = (
    profile: any,
    botState: any
): StrategyExplanation => {
    // 1. Check if paused
    if (!profile.is_active) {
        return {
            reason: 'Strategy is currently paused.',
            recommendation: 'Click the play button to start monitoring market signals.',
            severity: 'info'
        };
    }

    // 2. Check Daily Profit Target (Simulation/Logic based on profiles)
    // In a real system, we'd check the ledger, but here we can check the status message if provided in botState
    const profileStatus = botState?.profileStatuses?.[profile.id];

    if (profileStatus?.status === 'TARGET_REACHED') {
        return {
            reason: 'Daily profit target reached!',
            recommendation: 'Trading is paused until tomorrow to lock in your gains.',
            severity: 'success'
        };
    }

    if (profileStatus?.status === 'SESSION_RESTRICTED') {
        return {
            reason: 'Market is currently outside your allowed trading hours.',
            recommendation: 'The bot will resume automatically when your session opens.',
            severity: 'info'
        };
    }

    // 3. Rule Pass Ratio Logic
    const lastSignal = botState?.signals?.find((s: any) => s.profileId === profile.id);
    if (lastSignal) {
        const votingRules = profile.strategy_config?.rules?.filter((r: any) => r.ruleType === 'voting') || [];
        const passCount = lastSignal.metadata?.ruleStatuses?.filter((rs: any) => rs.passed && votingRules.some((vr: any) => vr.ruleId === rs.ruleId)).length || 0;
        const requiredPassRatio = profile.strategy_config?.execution?.minRulePassRatio || 1.0;
        const totalVoting = votingRules.length;
        const requiredCount = Math.ceil(totalVoting * requiredPassRatio);

        if (passCount < requiredCount) {
            return {
                reason: `Market conditions didn't meet your risk style (${passCount}/${requiredCount} indicators matched).`,
                recommendation: 'This is normal; the bot is waiting for a higher probability setup.',
                severity: 'info'
            };
        }

        if (lastSignal.direction === 'NEUTRAL') {
            return {
                reason: 'Indicators are active but showing conflicting signals.',
                recommendation: 'The bot requires alignment across your strategy rules before entering.',
                severity: 'info'
            };
        }
    }

    return {
        reason: 'Bot is active and monitoring live market data for a perfect setup.',
        severity: 'info'
    };
};
