bet / src /engine /schema.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
9.31 kB
import { parseOdds } from './math.js';
export const ALLOWED_LINES = new Set(['1.5', '2.5', '3.5', '4.5', '5.5']);
/**
* Extract JSON cleanly even if wrapped in markdown ```json fences or extra prose.
*/
export function extractJsonString(rawText) {
if (typeof rawText !== 'string') {
throw new Error('Input must be a JSON string or parsed object.');
}
const trimmed = rawText.trim();
if (!trimmed) {
throw new Error('Empty scout payload — expected a JSON slate.');
}
const fenceMatch = trimmed.match(/```(?:json)?\s*([\s\S]*?)```/i);
if (fenceMatch && fenceMatch[1]) {
return fenceMatch[1].trim();
}
const firstBrace = trimmed.indexOf('{');
const firstBracket = trimmed.indexOf('[');
let start = -1;
let end = -1;
if (firstBrace !== -1 && (firstBracket === -1 || firstBrace < firstBracket)) {
start = firstBrace;
end = trimmed.lastIndexOf('}');
} else if (firstBracket !== -1) {
start = firstBracket;
end = trimmed.lastIndexOf(']');
}
if (start === -1 || end === -1 || end <= start) {
throw new Error('Could not locate a JSON object or array in the scout output.');
}
return trimmed.slice(start, end + 1);
}
function toNumber(v, fallback = null) {
if (v === null || v === undefined || v === '') return fallback;
const n = Number(v);
return Number.isFinite(n) ? n : fallback;
}
function normalizeTeamStats(raw = {}, fallbackName = 'Team') {
const gp = toNumber(raw.gp, 0);
const gf = toNumber(raw.gf, null);
const ga = toNumber(raw.ga, null);
const xg = toNumber(raw.xg, null);
const xga = toNumber(raw.xga, null);
const outRaw = raw.confirmedOut || {};
const doubtRaw = raw.doubts5050 || {};
return {
name: String(raw.name || fallbackName).trim(),
gp,
gf,
ga,
xg,
xga,
venueGfPerGame: toNumber(raw.venueGfPerGame, null),
venueGaPerGame: toNumber(raw.venueGaPerGame, null),
managerGamesInCharge: toNumber(raw.managerGamesInCharge, 20),
newManagerTightenedDefense: Boolean(raw.newManagerTightenedDefense),
confirmedOut: {
gk: toNumber(outRaw.gk, 0),
startingCB: toNumber(outRaw.startingCB, 0),
otherDef: toNumber(outRaw.otherDef, 0),
mid: toNumber(outRaw.mid, 0),
topScorer: toNumber(outRaw.topScorer, 0),
otherAtt: toNumber(outRaw.otherAtt, 0),
names: Array.isArray(outRaw.names) ? outRaw.names.map(String) : [],
},
doubts5050: {
gk: toNumber(doubtRaw.gk, 0),
startingCB: toNumber(doubtRaw.startingCB, 0),
otherDef: toNumber(doubtRaw.otherDef, 0),
topScorer: toNumber(doubtRaw.topScorer, 0),
otherAtt: toNumber(doubtRaw.otherAtt, 0),
names: Array.isArray(doubtRaw.names) ? doubtRaw.names.map(String) : [],
},
keyStartersToConfirm: Array.isArray(raw.keyStartersToConfirm)
? raw.keyStartersToConfirm.map(String)
: [],
};
}
function normalizeTotals(totalsRaw = {}, warnings, matchLabel) {
const totals = {};
for (const [rawKey, lineObj] of Object.entries(totalsRaw || {})) {
const key = String(rawKey).trim();
if (!ALLOWED_LINES.has(key)) {
warnings.push(`${matchLabel}: skipped non-half-goal line "${key}" (only 1.5/2.5/3.5/4.5/5.5 allowed).`);
continue;
}
if (!lineObj || typeof lineObj !== 'object') continue;
const over = parseOdds(lineObj.over);
const under = parseOdds(lineObj.under);
const sportyOver = parseOdds(lineObj.sportybetOver);
const sportyUnder = parseOdds(lineObj.sportybetUnder);
const openOver = parseOdds(lineObj.openOver);
const openUnder = parseOdds(lineObj.openUnder);
if (!over && !under && !sportyOver && !sportyUnder) continue;
totals[key] = {
over: over || sportyOver,
under: under || sportyUnder,
sportybetOver: sportyOver || null,
sportybetUnder: sportyUnder || null,
openOver: openOver || null,
openUnder: openUnder || null,
simOverProb: toNumber(lineObj.simOverProb, null),
simUnderProb: toNumber(lineObj.simUnderProb, null),
};
}
return totals;
}
function normalizeMatch(raw, idx, warnings) {
const homeName = raw.home?.name || raw.homeTeam || `Home ${idx + 1}`;
const awayName = raw.away?.name || raw.awayTeam || `Away ${idx + 1}`;
const label = `${homeName} vs ${awayName}`;
const home = normalizeTeamStats(
typeof raw.home === 'object' ? raw.home : { name: homeName },
homeName
);
const away = normalizeTeamStats(
typeof raw.away === 'object' ? raw.away : { name: awayName },
awayName
);
const mlRaw = raw.moneyline || {};
const moneyline = {
home: parseOdds(mlRaw.home),
draw: parseOdds(mlRaw.draw),
away: parseOdds(mlRaw.away),
};
const totals = normalizeTotals(raw.totals, warnings, label);
if (Object.keys(totals).length === 0) {
warnings.push(`${label}: no valid half-goal Over/Under lines found.`);
}
const weatherRaw = raw.weather || {};
const precipRaw = String(weatherRaw.precipType || 'none').toLowerCase().trim();
const precipType = ['none', 'drizzle', 'rain', 'snow'].includes(precipRaw) ? precipRaw : 'none';
const hasVerifiedTeamNews =
raw.hasVerifiedTeamNews === undefined ? false : Boolean(raw.hasVerifiedTeamNews);
if (raw.hasVerifiedTeamNews === undefined) {
warnings.push(`${label}: hasVerifiedTeamNews omitted; defaulting to false (safety veto).`);
}
return {
id: String(raw.id || `m_${idx + 1}_${home.name.toLowerCase().replace(/[^a-z0-9]+/g, '_')}`),
espnEventId: raw.espnEventId ? String(raw.espnEventId) : null,
espnLeague: raw.espnLeague ? String(raw.espnLeague) : null,
kickoffIso: raw.kickoffIso ? String(raw.kickoffIso) : null,
label,
kickoffEAT: String(raw.kickoffEAT || 'TBD'),
league: String(raw.league || 'Unknown League'),
tier: toNumber(raw.tier, 1),
isReserveOrYouth: Boolean(raw.isReserveOrYouth),
isPostIntlBreak: Boolean(raw.isPostIntlBreak),
hasVerifiedTeamNews,
home,
away,
moneyline,
totals,
weather: {
tempC: toNumber(weatherRaw.tempC, 12),
windKmh: toNumber(weatherRaw.windKmh, 8),
precipType,
},
notes: String(raw.notes || ''),
actualScore: raw.actualScore || null,
};
}
function normalizeToken(str) {
return String(str || '')
.toLowerCase()
.normalize('NFD')
.replace(/[\u0300-\u036f]/g, '')
.replace(/[^a-z0-9]+/g, ' ')
.trim();
}
/**
* Attach ESPN eventId, league slug, and ISO kickoff time to scouted matches
* so overnight settlement grades every leg automatically.
*/
export function attachEspnMetadata(slate, espnFixtures = []) {
if (!espnFixtures || espnFixtures.length === 0) return slate;
const byId = new Map();
for (const fx of espnFixtures) {
if (fx.eventId) byId.set(String(fx.eventId), fx);
}
for (const match of slate.matches) {
let found = null;
if (match.espnEventId && byId.has(String(match.espnEventId))) {
found = byId.get(String(match.espnEventId));
} else if (match.id && byId.has(String(match.id))) {
found = byId.get(String(match.id));
}
if (!found) {
const hNorm = normalizeToken(match.home.name);
const aNorm = normalizeToken(match.away.name);
found = espnFixtures.find((fx) => {
const fxName = normalizeToken(fx.name || `${fx.homeTeam} vs ${fx.awayTeam}`);
const fxHome = normalizeToken(fx.homeTeam);
const fxAway = normalizeToken(fx.awayTeam);
const homeHit = hNorm && (fxHome.includes(hNorm) || hNorm.includes(fxHome) || fxName.includes(hNorm));
const awayHit = aNorm && (fxAway.includes(aNorm) || aNorm.includes(fxAway) || fxName.includes(aNorm));
return homeHit && awayHit;
});
}
if (found) {
match.espnEventId = String(found.eventId);
match.espnLeague = found.league;
match.kickoffIso = found.kickoffIso || match.kickoffIso;
if (!match.kickoffEAT || match.kickoffEAT === 'TBD') {
match.kickoffEAT = found.kickoffEAT || match.kickoffEAT;
}
if (!match.league || match.league === 'Unknown League') {
match.league = found.leagueName || match.league;
}
if (typeof found.tier === 'number') {
match.tier = found.tier;
}
}
}
return slate;
}
/**
* Parse and validate a Scout JSON payload (string or JS object).
*/
export function parseSlatePayload(input) {
let parsed;
if (typeof input === 'string') {
const jsonStr = extractJsonString(input);
try {
parsed = JSON.parse(jsonStr);
} catch (err) {
throw new Error(`Invalid JSON syntax: ${err.message}`);
}
} else if (input && typeof input === 'object') {
parsed = input;
} else {
throw new Error('Slate input must be a JSON string or object.');
}
const rawMatches = Array.isArray(parsed) ? parsed : parsed.matches;
if (!Array.isArray(rawMatches) || rawMatches.length === 0) {
throw new Error('Slate JSON must include a non-empty "matches" array.');
}
const warnings = [];
const matches = rawMatches.map((m, i) => normalizeMatch(m, i, warnings));
return {
slateDate: String(parsed.slateDate || new Date().toISOString().slice(0, 10)),
generatedAtEAT: String(parsed.generatedAtEAT || ''),
bookmaker: String(parsed.bookmaker || 'SportyBet TZ'),
matches,
warnings,
};
}