bet / src /scraper.js
eznd's picture
v2: Personal Scout-vs-Judge O/U risk-veto engine with Gemini 4 Hydrogen grounded scout
4039084
Raw History Blame Contribute Delete
12.8 kB
import axios from 'axios';
const EAT_OFFSET_MS = 3 * 60 * 60 * 1000;
const MATCH_DURATION_MINUTES = 120; // 90m + HT + stoppage
/**
* Curated liquid senior competitions ranked by liquidity & team-news reliability.
* Excludes youth/reserve/4th-tier leagues to keep pool quality high (20–100 matches target).
*/
export const LIQUID_LEAGUES = [
// Priority 100: Elite European & International Competitions (Tier 1)
{ slug: 'uefa.champions', tier: 1, priority: 100 },
{ slug: 'uefa.europa', tier: 1, priority: 98 },
{ slug: 'uefa.europa.conf', tier: 1, priority: 94 },
{ slug: 'eng.1', tier: 1, priority: 100 },
{ slug: 'esp.1', tier: 1, priority: 99 },
{ slug: 'ger.1', tier: 1, priority: 99 },
{ slug: 'ita.1', tier: 1, priority: 99 },
{ slug: 'fra.1', tier: 1, priority: 97 },
{ slug: 'uefa.nations', tier: 1, priority: 96 },
{ slug: 'fifa.world', tier: 1, priority: 100 },
{ slug: 'fifa.worldq.uefa', tier: 1, priority: 95 },
{ slug: 'fifa.worldq.conmebol', tier: 1, priority: 94 },
{ slug: 'uefa.euro', tier: 1, priority: 98 },
// Priority 80–90: Major European Top-Flight & Top-5 Second Divisions
{ slug: 'ned.1', tier: 1, priority: 90 },
{ slug: 'por.1', tier: 1, priority: 90 },
{ slug: 'bel.1', tier: 1, priority: 88 },
{ slug: 'tur.1', tier: 1, priority: 87 },
{ slug: 'sco.1', tier: 1, priority: 86 },
{ slug: 'eng.2', tier: 2, priority: 89 },
{ slug: 'ger.2', tier: 2, priority: 88 },
{ slug: 'esp.2', tier: 2, priority: 87 },
{ slug: 'ita.2', tier: 2, priority: 86 },
{ slug: 'fra.2', tier: 2, priority: 85 },
{ slug: 'eng.fa', tier: 1, priority: 88 },
{ slug: 'eng.league_cup', tier: 1, priority: 86 },
{ slug: 'esp.copa_del_rey', tier: 1, priority: 85 },
{ slug: 'ger.dfb_pokal', tier: 1, priority: 86 },
{ slug: 'ita.coppa_italia', tier: 1, priority: 85 },
{ slug: 'fra.coupe_de_france', tier: 1, priority: 84 },
// Priority 70–82: Strong European & Global Senior First Divisions
{ slug: 'aut.1', tier: 2, priority: 80 },
{ slug: 'sui.1', tier: 2, priority: 80 },
{ slug: 'gre.1', tier: 2, priority: 79 },
{ slug: 'den.1', tier: 2, priority: 78 },
{ slug: 'nor.1', tier: 2, priority: 77 },
{ slug: 'swe.1', tier: 2, priority: 77 },
{ slug: 'pol.1', tier: 2, priority: 76 },
{ slug: 'cze.1', tier: 2, priority: 75 },
{ slug: 'bra.1', tier: 1, priority: 84 },
{ slug: 'arg.1', tier: 1, priority: 82 },
{ slug: 'conmebol.libertadores', tier: 1, priority: 88 },
{ slug: 'conmebol.sudamericana', tier: 2, priority: 80 },
{ slug: 'usa.1', tier: 2, priority: 78 },
{ slug: 'mex.1', tier: 2, priority: 78 },
{ slug: 'fifa.friendly', tier: 2, priority: 74 },
// Priority 60–72: Reputable Secondary Global & Lower Tiers (helps reach 20–100 pool)
{ slug: 'eng.3', tier: 2, priority: 72 },
{ slug: 'ned.2', tier: 2, priority: 71 },
{ slug: 'tur.2', tier: 2, priority: 68 },
{ slug: 'ksa.1', tier: 2, priority: 72 },
{ slug: 'jpn.1', tier: 2, priority: 72 },
{ slug: 'kor.1', tier: 2, priority: 70 },
{ slug: 'aus.1', tier: 2, priority: 69 },
{ slug: 'afc.champions', tier: 2, priority: 75 },
{ slug: 'caf.champions', tier: 2, priority: 72 },
{ slug: 'concacaf.champions', tier: 2, priority: 72 },
];
const RESERVE_PATTERN = /\b(U17|U18|U19|U20|U21|U23|Reserves|Jong|Castilla|Atl[eé]tico B|II)\b/i;
export function formatEATDateTime(dateObj) {
return dateObj.toLocaleString('en-GB', {
timeZone: 'Africa/Dar_es_Salaam',
month: 'short',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
hour12: false,
}) + ' EAT';
}
export function formatEATTimeOnly(dateObj) {
return dateObj.toLocaleString('en-GB', {
timeZone: 'Africa/Dar_es_Salaam',
hour: '2-digit',
minute: '2-digit',
hour12: false,
}) + ' EAT';
}
export function getEATDateIso(dateObj = new Date()) {
const shifted = new Date(dateObj.getTime() + EAT_OFFSET_MS);
return shifted.toISOString().slice(0, 10);
}
/**
* Compute the exact kickoff eligibility window in UTC based on EAT rules:
* Default daily cycle: scout at 13:00 EAT -> matches starting >= 75 min later
* and finishing no later than 01:30 EAT tonight (latest kickoff 23:30 EAT).
*/
export function computeSlateWindow(now = new Date(), options = {}) {
const minLeadMinutes = Number(options.minLeadMinutes ?? process.env.MIN_LEAD_MINUTES ?? 75);
const finishDeadlineEAT = String(options.finishDeadlineEAT || process.env.FINISH_DEADLINE_EAT || '01:30').trim();
const explicitWindowHours = options.windowHours ? Number(options.windowHours) : null;
const earliestKickoff = new Date(now.getTime() + minLeadMinutes * 60_000);
let finishDeadline;
if (explicitWindowHours && Number.isFinite(explicitWindowHours)) {
finishDeadline = new Date(now.getTime() + explicitWindowHours * 3600_000);
} else {
const [hh, mm] = finishDeadlineEAT.split(':').map(Number);
const eatNow = new Date(now.getTime() + EAT_OFFSET_MS);
const y = eatNow.getUTCFullYear();
const m = eatNow.getUTCMonth();
const d = eatNow.getUTCDate();
// Target deadline in UTC corresponding to HH:MM EAT on same EAT calendar day
let candidateUtcMs = Date.UTC(y, m, d, hh || 1, mm || 30, 0) - EAT_OFFSET_MS;
// Advance to next day's deadline if already passed or less than 3 hours ahead
if (candidateUtcMs - now.getTime() < 3 * 3600_000) {
candidateUtcMs += 24 * 3600_000;
}
finishDeadline = new Date(candidateUtcMs);
}
const latestKickoff = new Date(finishDeadline.getTime() - MATCH_DURATION_MINUTES * 60_000);
return {
nowIso: now.toISOString(),
slateDate: getEATDateIso(now),
generatedAtEAT: formatEATTimeOnly(now),
minLeadMinutes,
finishDeadlineIso: finishDeadline.toISOString(),
finishDeadlineEAT: formatEATDateTime(finishDeadline),
earliestKickoff,
latestKickoff,
earliestKickoffEAT: formatEATDateTime(earliestKickoff),
latestKickoffEAT: formatEATDateTime(latestKickoff),
};
}
function toYyyymmddUtc(dateObj) {
return dateObj.toISOString().slice(0, 10).replace(/-/g, '');
}
async function fetchLeagueScoreboard(leagueCfg, dateStrings) {
const found = [];
for (const yyyymmdd of dateStrings) {
try {
const url = `https://site.api.espn.com/apis/site/v2/sports/soccer/${leagueCfg.slug}/scoreboard?dates=${yyyymmdd}`;
const res = await axios.get(url, { timeout: 10000 });
const events = res.data?.events || [];
const leagueName = res.data?.leagues?.[0]?.name || leagueCfg.slug;
for (const event of events) {
const comp = event.competitions?.[0];
const statusName = comp?.status?.type?.name || '';
if (['STATUS_POSTPONED', 'STATUS_CANCELED', 'STATUS_ABANDONED'].includes(statusName)) {
continue;
}
const competitors = comp?.competitors || [];
const homeComp = competitors.find((c) => c.homeAway === 'home') || competitors[0];
const awayComp = competitors.find((c) => c.homeAway === 'away') || competitors[1];
const homeTeam = homeComp?.team?.displayName || homeComp?.team?.name || 'Home';
const awayTeam = awayComp?.team?.displayName || awayComp?.team?.name || 'Away';
if (RESERVE_PATTERN.test(homeTeam) || RESERVE_PATTERN.test(awayTeam)) {
continue;
}
found.push({
eventId: String(event.id),
league: leagueCfg.slug,
leagueName,
tier: leagueCfg.tier,
priority: leagueCfg.priority,
homeTeam,
awayTeam,
team1Id: homeComp?.team?.id || null,
team2Id: awayComp?.team?.id || null,
name: `${homeTeam} vs ${awayTeam}`,
kickoffIso: event.date,
});
}
} catch {
// Quietly skip individual unavailable ESPN league endpoints
}
}
return found;
}
/**
* Scrape liquid senior fixtures inside the configured EAT finish-deadline window.
* Builds a ranked pool targeting 20–100 good matches and returns both the full pool
* and the top-ranked shortlist for deep grounded search scouting.
*/
export async function scrapeMatchPool(options = {}) {
const now = options.now ? new Date(options.now) : new Date();
const poolTargetMin = Number(options.poolTargetMin ?? process.env.POOL_TARGET_MIN ?? 20);
const poolMaxMatches = Number(options.poolMaxMatches ?? process.env.POOL_MAX_MATCHES ?? 100);
const deepScoutMax = Number(options.deepScoutMax ?? process.env.DEEP_SCOUT_MAX_MATCHES ?? 24);
const windowInfo = computeSlateWindow(now, options);
// Collect all unique UTC calendar dates spanned by [earliestKickoff, latestKickoff]
const dateSet = new Set();
const cursor = new Date(windowInfo.earliestKickoff.getTime() - 12 * 3600_000);
const endCursor = new Date(windowInfo.latestKickoff.getTime() + 12 * 3600_000);
while (cursor <= endCursor) {
dateSet.add(toYyyymmddUtc(cursor));
cursor.setUTCDate(cursor.getUTCDate() + 1);
}
const dateStrings = Array.from(dateSet);
// Fetch leagues in bounded parallel batches of 8
const rawFixtures = [];
const batchSize = 8;
for (let i = 0; i < LIQUID_LEAGUES.length; i += batchSize) {
const chunk = LIQUID_LEAGUES.slice(i, i + batchSize);
const results = await Promise.all(chunk.map((l) => fetchLeagueScoreboard(l, dateStrings)));
for (const arr of results) rawFixtures.push(...arr);
}
// Deduplicate by eventId and filter strictly into [earliestKickoff, latestKickoff]
const seen = new Set();
const eligible = [];
for (const fx of rawFixtures) {
if (seen.has(fx.eventId)) continue;
seen.add(fx.eventId);
const kickoff = new Date(fx.kickoffIso);
if (Number.isNaN(kickoff.getTime())) continue;
if (kickoff < windowInfo.earliestKickoff || kickoff > windowInfo.latestKickoff) continue;
const hoursAhead = (kickoff.getTime() - now.getTime()) / 3600_000;
const kickoffEAT = formatEATDateTime(kickoff);
eligible.push({
...fx,
kickoffMs: kickoff.getTime(),
kickoffEAT,
hoursAhead: +hoursAhead.toFixed(1),
description: `${fx.homeTeam} vs ${fx.awayTeam} - ${fx.leagueName} (${kickoffEAT})`,
});
}
// Sort by liquidity priority desc, then earliest kickoff asc
eligible.sort((a, b) => {
if (b.priority !== a.priority) return b.priority - a.priority;
return a.kickoffMs - b.kickoffMs;
});
const pool = eligible.slice(0, poolMaxMatches);
const shortlisted = pool.slice(0, Math.min(deepScoutMax, pool.length));
return {
pool,
shortlisted,
windowInfo,
stats: {
totalEligible: eligible.length,
poolCount: pool.length,
shortlistedCount: shortlisted.length,
poolTargetMin,
poolMaxMatches,
metSoftTarget: pool.length >= poolTargetMin,
},
};
}
/**
* Lightweight ESPN final-score fetch for deterministic settlement.
*/
export async function fetchEspnMatchResult(league, eventId) {
if (!league || !eventId) return null;
try {
const url = `https://site.api.espn.com/apis/site/v2/sports/soccer/${league}/summary?event=${eventId}`;
const res = await axios.get(url, { timeout: 10000 });
const data = res.data;
const comp = data?.header?.competitions?.[0];
if (!comp) return null;
const statusType = comp.status?.type || {};
const statusName = statusType.name || '';
const isPostponed = ['STATUS_POSTPONED', 'STATUS_CANCELED', 'STATUS_ABANDONED'].includes(statusName);
const completed = Boolean(statusType.completed);
const competitors = comp.competitors || [];
const homeComp = competitors.find((c) => c.homeAway === 'home') || competitors[0];
const awayComp = competitors.find((c) => c.homeAway === 'away') || competitors[1];
const homeScore = homeComp?.score !== undefined ? Number(homeComp.score) : null;
const awayScore = awayComp?.score !== undefined ? Number(awayComp.score) : null;
let htScoreStr = '';
if (homeComp?.linescores?.length > 0 && awayComp?.linescores?.length > 0) {
const getVal = (l) => (typeof l === 'object' ? (l.value ?? l.displayValue ?? l.score ?? 0) : (l ?? 0));
htScoreStr = ` (HT: ${getVal(homeComp.linescores[0])}-${getVal(awayComp.linescores[0])})`;
}
return {
completed,
isPostponed,
statusName,
matchDate: comp.date || null,
homeTeam: homeComp?.team?.displayName || homeComp?.team?.name || 'Home',
awayTeam: awayComp?.team?.displayName || awayComp?.team?.name || 'Away',
homeScore,
awayScore,
scoreLabel:
isPostponed
? 'Postponed'
: homeScore !== null && awayScore !== null
? `${homeScore}-${awayScore}${htScoreStr}`
: null,
};
} catch (err) {
console.warn(`[ESPN] Failed to fetch summary for ${league}/${eventId}: ${err.message}`);
return null;
}
}