/**
 * Results generator — runs daily ~9 AM ET via n8n.
 *
 * 1. Query yesterday's resolved grades from the Ledger.
 * 2. Compute hits / misses / accuracy / CLV summary.
 * 3. Build a recap share card.
 * 4. Return { data, imageBuffer, imageUrl } for downstream channels.
 */

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

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

function yesterdayISO() {
  const d = new Date(Date.now() - 24 * 60 * 60_000);
  return d.toISOString().slice(0, 10);
}

function dateLabel(iso) {
  return new Date(`${iso}T12:00:00Z`).toLocaleDateString('en-US', {
    month: 'long', day: 'numeric', year: 'numeric', timeZone: 'America/New_York',
  });
}

async function fetchLedgerForDate(date) {
  const res = await axios.get(`${API_BASE}/api/ledger?date=${date}`, { timeout: 10_000 }).catch(() => null);
  const rows = Array.isArray(res?.data?.entries) ? res.data.entries : [];
  return rows;
}

function summarize(entries) {
  const hits = entries.filter((e) => e.result === 'hit').length;
  const misses = entries.filter((e) => e.result === 'miss').length;
  const total = hits + misses;
  return {
    total,
    hits,
    misses,
    accuracy: total ? Math.round((hits / total) * 100) : 0,
  };
}

async function generate({ format = 'square', date = null } = {}) {
  const iso = date || yesterdayISO();
  const raw = await fetchLedgerForDate(iso);
  const stats = summarize(raw);

  const payload = {
    date: dateLabel(iso),
    accuracy: stats.accuracy,
    entries: raw.slice(0, 6).map((e) => ({
      player: e.player_name || e.player,
      stat: e.stat_type || e.stat,
      direction: e.direction,
      line: e.line,
      grade: e.grade,
      result: e.result,
    })),
  };

  let card = null;
  try {
    card = await buildCard({ type: 'recap', format, payload });
  } catch (err) {
    console.error('[resultsGenerator] card build failed:', err.message);
  }

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

module.exports = { generate };
