import { query } from '../../db';
import { alerter, BriefPayload } from '../../services/alerter';

export async function sendDailyBrief(): Promise<void> {
  try {
    const sections: BriefPayload['sections'] = [];

    // 1. Edge Report
    const edgeResult = await query(`
      SELECT league, avg_clv, positive_clv_rate, edge_trend, sample_size
      FROM sc_edge_metrics
      WHERE metric_date = CURRENT_DATE - 1 AND window_size = 50
      ORDER BY league
    `);

    if (edgeResult.rows.length > 0) {
      const lines = edgeResult.rows.map(r =>
        `${r.league.toUpperCase()}: CLV ${parseFloat(r.avg_clv).toFixed(2)} | +CLV ${(parseFloat(r.positive_clv_rate) * 100).toFixed(0)}% | ${r.edge_trend} (n=${r.sample_size})`
      );
      sections.push({ title: '📈 Edge Report', content: lines.join('\n') });
    } else {
      sections.push({ title: '📈 Edge Report', content: 'No CLV data for yesterday' });
    }

    // 2. Pipeline Health
    const stateResult = await query(`SELECT * FROM sc_global_state WHERE id = 'primary'`);
    const state = stateResult.rows[0];
    sections.push({
      title: '🏥 Pipeline Health',
      content: [
        `Mode: ${state?.mode || 'unknown'}`,
        `Infra: ${state?.infra_health_score || '?'}/100`,
        `Data: ${state?.data_integrity_score || '?'}/100`,
        `Edge: ${state?.edge_health_score || '?'}/100`,
      ].join('\n'),
    });

    // 3. Missed Opportunities
    const missedResult = await query(`
      SELECT o.opportunity_type, o.book, o.score, o.edge_estimate
      FROM sc_opportunities o
      WHERE o.status = 'expired' AND o.score > 70
        AND o.created_at > NOW() - INTERVAL '24 hours'
      ORDER BY o.score DESC LIMIT 5
    `);

    if (missedResult.rows.length > 0) {
      const lines = missedResult.rows.map(r =>
        `${r.book} | ${r.opportunity_type} | Score: ${parseFloat(r.score).toFixed(0)} | Edge: ${parseFloat(r.edge_estimate).toFixed(1)}pts`
      );
      sections.push({ title: '❌ Missed Opportunities', content: lines.join('\n') });
    } else {
      sections.push({ title: '❌ Missed Opportunities', content: 'None (score >70)' });
    }

    // 4. Today's Slate
    const slateResult = await query(`
      SELECT COUNT(*) as game_count,
             COUNT(DISTINCT league) as league_count
      FROM "SportsGame"
      WHERE "gameDate"::date = CURRENT_DATE
    `);
    const gameCount = parseInt(slateResult.rows[0]?.game_count || '0');
    const leagueCount = parseInt(slateResult.rows[0]?.league_count || '0');

    const earlySignals = await query(`
      SELECT COUNT(*) as count FROM sc_opportunities
      WHERE status = 'open' AND score > 60
    `);

    sections.push({
      title: '📅 Today\'s Slate',
      content: `${gameCount} games across ${leagueCount} leagues\n${earlySignals.rows[0]?.count || 0} early opportunity signals`,
    });

    // 5. Risk State
    const riskResult = await query(`
      SELECT risk_level, drawdown_pct, daily_exposure, recommendation
      FROM sc_risk_state
      WHERE state_date = CURRENT_DATE - 1
    `);

    if (riskResult.rows.length > 0) {
      const r = riskResult.rows[0];
      sections.push({
        title: '🛡️ Risk State',
        content: `Level: ${r.risk_level}\nDrawdown: ${r.drawdown_pct}%\nExposure: ${r.daily_exposure}\n${r.recommendation}`,
      });
    }

    // 6. Data Quality
    const eventSummary = await query(`
      SELECT severity, COUNT(*) as count
      FROM sc_system_events
      WHERE created_at > NOW() - INTERVAL '24 hours'
        AND event_type NOT IN ('task_complete', 'stale_lock_cleared')
      GROUP BY severity
    `);

    const evtLines = eventSummary.rows.map(r => `${r.severity}: ${r.count}`);
    sections.push({
      title: '🔧 System Events (24h)',
      content: evtLines.length > 0 ? evtLines.join(' | ') : 'No events',
    });

    // Send to all admins
    const admins = await query(`SELECT telegram_chat_id FROM sc_users WHERE role = 'admin' AND telegram_chat_id IS NOT NULL`);

    for (const admin of admins.rows) {
      await alerter.sendDailyBrief(admin.telegram_chat_id, { sections });
    }

    await alerter.logEvent(
      'daily_brief_sent', 'info', 'daily-brief',
      `Morning brief sent to ${admins.rows.length} admins`,
      { admin_count: admins.rows.length, section_count: sections.length }
    );
  } catch (err) {
    console.error('[daily-brief] Error:', err);
    throw err;
  }
}
