/**
 * Cheatsheet generator — runs daily ~4:30 PM ET via n8n.
 *
 * 1. Pull top-graded props for tonight (default limit 8).
 * 2. Synthesize structured cheatsheet payload.
 * 3. Build a share card via the local share-card endpoint.
 * 4. Return { data, imageUrl, imageBuffer } so downstream consumers
 *    (email, telegram, discord) can fan out.
 *
 * No I/O side effects. Caller decides what to push where.
 */

const axios = require('axios');
const { buildCard, publicCardUrl } = require('./_shareCardClient');

const API_BASE = process.env.API_BASE_URL || 'http://localhost:4000';

async function fetchTopGraded(limit = 8, sport = null) {
  const params = new URLSearchParams({ limit: String(limit) });
  if (sport) params.set('sport', sport);
  const res = await axios.get(`${API_BASE}/api/props/top-graded?${params}`, { timeout: 10_000 });
  return Array.isArray(res.data?.props) ? res.data.props : [];
}

function todayLabel(now = new Date()) {
  return now.toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric', timeZone: 'America/New_York' });
}

async function generate({ limit = 8, sport = null, format = 'square' } = {}) {
  const grades = await fetchTopGraded(limit, sport);
  const payload = {
    date: todayLabel(),
    gameCount: new Set(grades.map((g) => g.game_id)).size,
    grades: grades.map((g) => ({
      grade: g.grade,
      player: g.player_name || g.player,
      stat: g.stat_type || g.stat,
      direction: g.direction,
      line: g.line,
    })),
  };

  let card = null;
  try {
    card = await buildCard({ type: 'cheatsheet', format, payload });
  } catch (err) {
    // Don't sink the generator if the card can't render — surface the data,
    // let the caller decide whether to push text-only.
    console.error('[cheatsheetGenerator] card build failed:', err.message);
  }

  return {
    data: payload,
    imageBuffer: card?.buffer || null,
    imageContentType: card?.contentType || null,
    imageUrl: publicCardUrl({ type: 'cheatsheet', format, payload }),
  };
}

module.exports = { generate };
