File size: 21,598 Bytes
4039084
 
 
 
 
 
 
 
 
044efc3
4039084
 
044efc3
 
4039084
 
 
044efc3
 
4039084
 
 
 
 
 
 
 
 
 
 
 
 
 
44b721f
4039084
 
 
 
 
 
 
 
 
 
 
 
 
 
44b721f
4039084
 
 
 
 
 
 
 
 
 
 
 
3365da7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4039084
 
 
 
 
 
 
 
 
 
 
 
 
 
3365da7
 
4039084
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3365da7
 
4039084
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
import { deVigTwoWay, solveImpliedLambda } from './math.js';

/**
 * Configurable presets matching betting modes.
 * Default: "sniper" (1.50 - 1.85, 1-2 legs max, strict CLEAN legs only).
 */
export const PRESETS = {
  sniper: {
    id: 'sniper',
    name: 'Single Best Sniper (1.50–1.85, 1 CLEAN pick)',
    minOdds: 1.50,
    maxOdds: 1.85,
    maxLegs: 1,
    minFairProb: 0.52,
    maxVigPct: 7.0,
    strictMode: true,
    allowCaution: false,
    minSlipAdjProb: 0.54,
    includeAlternative: false,
    singlePreferenceGap: 0.015,
    retailHaircut: 0.02,
  },
  balanced: {
    id: 'balanced',
    name: 'Balanced Cushion (2.00–2.60)',
    minOdds: 2.00,
    maxOdds: 2.60,
    maxLegs: 3,
    minFairProb: 0.62,
    maxVigPct: 7.5,
    strictMode: false,
    allowCaution: true,
    minSlipAdjProb: 0.36,
    includeAlternative: true,
    singlePreferenceGap: 0.01,
    retailHaircut: 0.025,
  },
  classic3x: {
    id: 'classic3x',
    name: 'Classic 3x (3.05–3.45)',
    minOdds: 3.05,
    maxOdds: 3.45,
    maxLegs: 3,
    minFairProb: 0.60,
    maxVigPct: 7.5,
    strictMode: false,
    allowCaution: true,
    minSlipAdjProb: 0.25,
    includeAlternative: true,
    singlePreferenceGap: 0.01,
    retailHaircut: 0.025,
  },
};

const MAX_POSITIVE_BONUS = 0.02; // Strictly capped at +2.0 pp to eliminate confirmation bias
const SOFT_PENALTY_VETO_THRESHOLD = 0.045; // >= 4.5 pp cumulative penalty triggers VETO

function computeTeamDerived(team) {
  const gp = team.gp || 0;
  const gfPerGame = gp > 0 && team.gf !== null ? team.gf / gp : team.venueGfPerGame;
  const gaPerGame = gp > 0 && team.ga !== null ? team.ga / gp : team.venueGaPerGame;

  const rawHasXg = gp >= 5 && team.gf !== null && team.xg !== null;
  const rawHasXga = gp >= 5 && team.ga !== null && team.xga !== null;

  const rawXgPg = rawHasXg ? team.xg / gp : null;
  const rawXgaPg = rawHasXga ? team.xga / gp : null;

  // Guard against cross-competition data mixing (e.g. 12-game domestic GF paired with 4-game UCL xG)
  const xgMismatch =
    rawHasXg &&
    gp >= 6 &&
    gfPerGame !== null &&
    rawXgPg > 0 &&
    gfPerGame - rawXgPg >= 1.0 &&
    team.gf / team.xg >= 1.8;

  const xgaMismatch =
    rawHasXga &&
    gp >= 6 &&
    gaPerGame !== null &&
    rawXgaPg > 0 &&
    gaPerGame - rawXgaPg >= 1.0 &&
    team.ga / team.xga >= 1.8;

  const hasXg = rawHasXg && !xgMismatch;
  const hasXga = rawHasXga && !xgaMismatch;

  const xgPerGame = hasXg ? rawXgPg : null;
  const xgaPerGame = hasXga ? rawXgaPg : null;

  const attDiff = hasXg ? team.gf - team.xg : null;
  const defLuck = hasXga ? team.ga - team.xga : null;
  const startingDefOut = (team.confirmedOut.startingCB || 0) + (team.confirmedOut.otherDef || 0);

  return {
    gp,
    gfPerGame,
    gaPerGame,
    xgPerGame,
    xgaPerGame,
    attDiff,
    defLuck,
    startingDefOut,
    xgMismatch,
    xgaMismatch,
  };
}

function summarizeKeyDriver(match, isOver, line, impliedLambda, combinedXgPg, combinedXgaPg, bonuses) {
  const parts = [`Implied total ${impliedLambda.toFixed(2)} goals`];
  if (combinedXgPg !== null) {
    parts.push(`combined xG ${combinedXgPg.toFixed(2)}/g`);
  }
  if (combinedXgaPg !== null) {
    parts.push(`xGA ${combinedXgaPg.toFixed(2)}/g`);
  }
  if (bonuses.length > 0) {
    parts.push(bonuses[0].reason);
  } else if (match.notes) {
    parts.push(match.notes.slice(0, 110));
  }
  return parts.join(' · ');
}

function summarizeFailureRisk(hardVetoes, softFlags, isOver, line) {
  if (hardVetoes.length > 0) return hardVetoes[0].reason;
  if (softFlags.length > 0) return softFlags[0].reason;
  return isOver
    ? `Early red card or low-tempo game stalling under ${line} goals.`
    : `Early penalty or late transition burst pushing total past ${line} goals.`;
}

/**
 * Evaluate a single (match, lineKey, side) candidate deterministically.
 */
export function evaluateLeg(match, lineKey, side, configInput = {}) {
  const config = { ...PRESETS.sniper, ...configInput };
  const line = Number(lineKey);
  const lineData = match.totals[lineKey];
  if (!lineData) return null;

  const dv = deVigTwoWay(lineData.over, lineData.under);
  if (!dv) return null;

  const isOver = side === 'over';
  const odds = isOver ? dv.overOdds : dv.underOdds;
  if (!odds) return null;

  const explicitSportyOdds = isOver ? lineData.sportybetOver : lineData.sportybetUnder;
  const floorOdds = explicitSportyOdds
    ? explicitSportyOdds
    : +(Math.max(1.02, 1 + (odds - 1) * (1 - config.retailHaircut))).toFixed(2);

  const fairProb = isOver ? dv.fairOver : dv.fairUnder;
  const simProb = isOver ? lineData.simOverProb : lineData.simUnderProb;
  const impliedLambda = +solveImpliedLambda(line, dv.fairOver).toFixed(2);

  const openOdds = isOver ? lineData.openOver : lineData.openUnder;
  const driftAgainst = openOdds ? +(odds - openOdds).toFixed(3) : 0;
  const driftWith = openOdds ? +(openOdds - odds).toFixed(3) : 0;

  const h = computeTeamDerived(match.home);
  const a = computeTeamDerived(match.away);

  const combinedXgPg = h.xgPerGame !== null && a.xgPerGame !== null ? h.xgPerGame + a.xgPerGame : null;
  const combinedXgaPg = h.xgaPerGame !== null && a.xgaPerGame !== null ? h.xgaPerGame + a.xgaPerGame : null;

  const hardVetoes = [];
  const softFlags = [];
  const bonuses = [];

  const addVeto = (code, reason) => hardVetoes.push({ code, reason });
  const addSoft = (code, penaltyPp, reason) => softFlags.push({ code, penaltyPp, reason });
  const addBonus = (code, bonusPp, reason) => bonuses.push({ code, bonusPp, reason });

  // =========================================================================
  // 1. UNIVERSAL HARD VETOES
  // =========================================================================
  if (!match.hasVerifiedTeamNews) {
    addVeto('NO_VERIFIED_TEAM_NEWS', 'No verified pre-match injury or team-news sheet.');
  }
  if (match.isReserveOrYouth) {
    addVeto('RESERVE_OR_YOUTH', 'Reserve or youth team fixture (high lineup volatility).');
  }
  if (dv.vigPct > config.maxVigPct) {
    addVeto(
      'EXCESSIVE_VIG',
      `Bookmaker margin is ${dv.vigPct.toFixed(1)}% (exceeds ${config.maxVigPct.toFixed(1)}% cap).`
    );
  }
  if (fairProb < config.minFairProb) {
    addVeto(
      'BELOW_FAIR_PROB_FLOOR',
      `De-vigged fair probability is ${(fairProb * 100).toFixed(1)}% (below ${(config.minFairProb * 100).toFixed(0)}% floor).`
    );
  }
  if (driftAgainst >= 0.08) {
    addVeto(
      'SHARP_DRIFT_AGAINST',
      `Sharp market drifted +${driftAgainst.toFixed(2)} against this side (${openOdds.toFixed(2)} -> ${odds.toFixed(2)}).`
    );
  }

  // =========================================================================
  // 2. DIRECTION-SPECIFIC SYMMETRIC HARD VETOES & SOFT PENALTIES
  // =========================================================================
  if (isOver) {
    const maxAttBubble = Math.max(
      h.attDiff !== null ? h.attDiff : -99,
      a.attDiff !== null ? a.attDiff : -99
    );
    const bubbleThreshold = line >= 2.5 ? 5.0 : 6.5;
    if (maxAttBubble >= bubbleThreshold) {
      const culprit =
        (h.attDiff !== null && h.attDiff >= bubbleThreshold ? `${match.home.name} (+${h.attDiff.toFixed(1)})` : '') ||
        `${match.away.name} (+${a.attDiff.toFixed(1)})`;
      addVeto(
        'ATT_XG_BUBBLE',
        `Attacking finishing bubble >= +${bubbleThreshold.toFixed(1)} goals above xG (${culprit}).`
      );
    } else if (maxAttBubble >= 3.5 && line >= 2.5) {
      addSoft(
        'MILD_ATT_XG_BUBBLE',
        2.0,
        `Elevated finishing overperformance (+${maxAttBubble.toFixed(1)} goals vs xG).`
      );
    }

    const homeNewTight = match.home.managerGamesInCharge <= 3 && match.home.newManagerTightenedDefense;
    const awayNewTight = match.away.managerGamesInCharge <= 3 && match.away.newManagerTightenedDefense;
    if (homeNewTight || awayNewTight) {
      const teamName = homeNewTight ? match.home.name : match.away.name;
      addVeto(
        'NEW_MGR_TIGHTENED_DEFENSE',
        `${teamName} hired a new manager within last 3 games who tightened defensive structure.`
      );
    }

    const topOut = (match.home.confirmedOut.topScorer || 0) + (match.away.confirmedOut.topScorer || 0);
    const topDoubt = (match.home.doubts5050.topScorer || 0) + (match.away.doubts5050.topScorer || 0);
    if (line >= 2.5 && topOut >= 1) {
      addVeto('TOP_SCORER_OUT', 'Confirmed absence of a primary top scorer on an Over 2.5+ line.');
    } else if (line >= 2.5 && topDoubt >= 1) {
      if (config.strictMode) {
        addVeto('TOP_SCORER_5050_DOUBT', 'Primary striker is a 50/50 fitness doubt on an Over 2.5+ line.');
      } else {
        addSoft('TOP_SCORER_5050_DOUBT', 3.0, 'Primary striker is a 50/50 fitness doubt (verify at T-60).');
      }
    } else if (topOut >= 1 && line <= 1.5) {
      addSoft('TOP_SCORER_OUT_O15', 2.0, 'Primary top scorer ruled out.');
    }

    const w = match.weather;
    if (line >= 2.5 && (w.precipType === 'snow' || (w.precipType === 'rain' && w.windKmh >= 25))) {
      addVeto('SEVERE_WEATHER_OVER', `Adverse pitch weather (${w.precipType}, ${w.tempC}°C, ${w.windKmh} km/h wind).`);
    } else if (w.tempC <= 2 || w.windKmh >= 22 || w.precipType === 'rain' || w.precipType === 'snow') {
      addSoft('WEATHER_DRAG_OVER', 1.5, `Scoring drag from weather (${w.tempC}°C, ${w.precipType}, ${w.windKmh} km/h).`);
    }

    if (line >= 2.5 && combinedXgPg !== null && combinedXgaPg !== null && combinedXgPg < 2.35 && combinedXgaPg < 2.35) {
      addVeto(
        'LOW_UNDERLYING_XG',
        `Combined underlying xG (${combinedXgPg.toFixed(2)}/g) and xGA (${combinedXgaPg.toFixed(2)}/g) are too low for Over ${line}.`
      );
    }

    if (match.isPostIntlBreak) {
      addSoft('POST_INTL_BREAK_RUST', 2.0, 'First match after international break (elevated attacking rust risk).');
    }
    if (match.home.managerGamesInCharge <= 2 || match.away.managerGamesInCharge <= 2) {
      if (!homeNewTight && !awayNewTight) {
        addSoft('NEW_MGR_UNCERTAINTY', 2.0, 'Manager has <= 2 games in charge (tactical unpredictability).');
      }
    }
    const otherAttOut = (match.home.confirmedOut.otherAtt || 0) + (match.away.confirmedOut.otherAtt || 0);
    const otherAttDoubt = (match.home.doubts5050.otherAtt || 0) + (match.away.doubts5050.otherAtt || 0);
    if (line >= 2.5 && (otherAttOut >= 2 || otherAttDoubt >= 2)) {
      addSoft('ATTACKING_DEPTH_LOSS', 2.0, 'Multiple secondary attackers injured or doubtful.');
    }
    if (
      line >= 2.5 &&
      ((h.gfPerGame !== null && h.gfPerGame < 0.85) || (a.gfPerGame !== null && a.gfPerGame < 0.85))
    ) {
      addSoft('ONE_SIDED_ATTACK_O25', 2.0, 'One side averages under 0.85 goals/game (Over 2.5 relies heavily on one team).');
    }

    if (combinedXgaPg !== null && combinedXgaPg >= 3.10 && maxAttBubble < 3.0) {
      addBonus('LEAKY_UNDERLYING_DEFENSES', 0.5, `High combined xGA (${combinedXgaPg.toFixed(2)}/g) without finishing bubble.`);
    }
    if (match.home.confirmedOut.startingCB >= 1 || match.away.confirmedOut.startingCB >= 1) {
      addBonus('DEFENDER_OUT_FOR_OVER', 0.5, 'Confirmed starting center-back absence supports goal volume.');
    }
  } else {
    // --- UNDER HARD VETOES ---
    const minMl = Math.min(
      match.moneyline.home || 99,
      match.moneyline.away || 99
    );
    const o25Odds = match.totals['2.5']?.over || null;
    if (minMl < 1.45 && o25Odds !== null && o25Odds < 1.50) {
      addVeto(
        'HEAVY_FAVORITE_BLOWOUT',
        `Heavy favorite (ML ${minMl.toFixed(2)}) with short Over 2.5 (${o25Odds.toFixed(2)}) carries 4-0/4-1 blowout risk.`
      );
    }

    if (combinedXgaPg !== null && combinedXgaPg >= 3.10) {
      addVeto(
        'HIGH_COMBINED_XGA',
        `Combined season xGA is ${combinedXgaPg.toFixed(2)}/game (>= 3.10 porous-defense cutoff).`
      );
    }
    if (
      (h.gp >= 6 && h.gaPerGame !== null && h.gaPerGame >= 2.00) ||
      (a.gp >= 6 && a.gaPerGame !== null && a.gaPerGame >= 2.00)
    ) {
      const leaky =
        h.gp >= 6 && h.gaPerGame >= 2.00
          ? `${match.home.name} (${h.gaPerGame.toFixed(2)} GA/g)`
          : `${match.away.name} (${a.gaPerGame.toFixed(2)} GA/g)`;
      addVeto('POROUS_DEFENSE_GA', `${leaky} concedes >= 2.00 goals per game.`);
    }

    const bothMissingCB =
      match.home.confirmedOut.startingCB >= 1 && match.away.confirmedOut.startingCB >= 1;
    const eitherMissing2Def = h.startingDefOut >= 2 || a.startingDefOut >= 2;
    const gkOut = match.home.confirmedOut.gk >= 1 || match.away.confirmedOut.gk >= 1;
    if (bothMissingCB) {
      addVeto('BOTH_STARTING_CBS_OUT', 'Both teams are missing a confirmed starting center-back.');
    } else if (eitherMissing2Def) {
      const depleted = h.startingDefOut >= 2 ? match.home.name : match.away.name;
      addVeto('DEFENSIVE_UNIT_DEPLETED', `${depleted} is missing 2+ starting defenders.`);
    } else if (gkOut) {
      addVeto('STARTING_GK_OUT', 'First-choice goalkeeper is ruled out on an Under line.');
    }

    const homeLuckyWithOut = h.defLuck !== null && h.defLuck <= -5.0 && h.startingDefOut >= 1;
    const awayLuckyWithOut = a.defLuck !== null && a.defLuck <= -5.0 && a.startingDefOut >= 1;
    const combDefLuck = h.defLuck !== null && a.defLuck !== null ? h.defLuck + a.defLuck : null;

    if (homeLuckyWithOut || awayLuckyWithOut) {
      const culprit = homeLuckyWithOut
        ? `${match.home.name} (${h.defLuck.toFixed(1)} GA vs xGA + defender out)`
        : `${match.away.name} (${a.defLuck.toFixed(1)} GA vs xGA + defender out)`;
      addVeto('DEF_XGA_LUCK_PLUS_INJURY', `Defensive luck bubble colliding with defensive absence: ${culprit}.`);
    } else if (combDefLuck !== null && combDefLuck <= -7.5) {
      addVeto(
        'COMBINED_DEF_XGA_LUCK',
        `Combined defenses are running ${combDefLuck.toFixed(1)} goals lucky vs xGA (high snap-back risk).`
      );
    } else {
      const worstDefLuck = Math.min(
        h.defLuck !== null ? h.defLuck : 0,
        a.defLuck !== null ? a.defLuck : 0
      );
      if (worstDefLuck <= -4.5) {
        addSoft(
          'MILD_DEF_XGA_LUCK',
          2.5,
          `One defense is outperforming xGA by ${worstDefLuck.toFixed(1)} goals (regression watch).`
        );
      }
    }

    const homeRebound =
      h.attDiff !== null &&
      (h.attDiff <= -8.0 ||
        (h.attDiff <= -6.0 && (a.xgaPerGame === null || a.xgaPerGame >= 1.15 || match.away.confirmedOut.startingCB >= 1)));
    const awayRebound =
      a.attDiff !== null &&
      (a.attDiff <= -8.0 ||
        (a.attDiff <= -6.0 && (h.xgaPerGame === null || h.xgaPerGame >= 1.15 || match.home.confirmedOut.startingCB >= 1)));
    if (homeRebound || awayRebound) {
      const culprit = homeRebound
        ? `${match.home.name} (${h.attDiff.toFixed(1)} GF vs xG)`
        : `${match.away.name} (${a.attDiff.toFixed(1)} GF vs xG)`;
      addVeto('ATT_REBOUND_RISK', `${culprit} is heavily under-scoring xG and due for upward finishing regression.`);
    }

    const maxXgCap = line <= 2.5 ? 2.75 : 3.25;
    if (combinedXgPg !== null && combinedXgPg >= maxXgCap) {
      addVeto(
        'HIGH_COMBINED_XG',
        `Combined attacking creation (${combinedXgPg.toFixed(2)} xG/g) exceeds safe Under ${line} ceiling (${maxXgCap}).`
      );
    }

    const totalCbOut = match.home.confirmedOut.startingCB + match.away.confirmedOut.startingCB;
    if (totalCbOut === 1 && !bothMissingCB && !eitherMissing2Def) {
      addSoft('SINGLE_CB_OUT', 2.0, 'One starting center-back confirmed out.');
    }
    const defDoubts =
      match.home.doubts5050.startingCB +
      match.away.doubts5050.startingCB +
      match.home.doubts5050.gk +
      match.away.doubts5050.gk;
    if (defDoubts >= 1) {
      addSoft('DEFENSIVE_DOUBT', 1.5, 'Starting center-back or goalkeeper listed as 50/50 doubt.');
    }
    if (match.home.managerGamesInCharge <= 2 || match.away.managerGamesInCharge <= 2) {
      addSoft('NEW_MGR_DEBUT_UNDER', 2.5, 'New manager debut (<= 2 games) adds tactical script volatility.');
    }

    const attOut = match.home.confirmedOut.topScorer + match.away.confirmedOut.topScorer;
    if (attOut >= 1) {
      addBonus('TOP_SCORER_OUT_FOR_UNDER', 1.0, 'Confirmed absence of a primary goalscorer suppresses ceiling.');
    }
    const w = match.weather;
    if ((w.tempC <= 3 || w.precipType !== 'none') && w.windKmh >= 15) {
      addBonus('ADVERSE_WEATHER_UNDER', 0.5, `Cold/windy conditions (${w.tempC}°C, ${w.windKmh} km/h) suppress tempo.`);
    }
  }

  // Universal soft flags & sharp steam
  if (driftAgainst >= 0.04 && driftAgainst < 0.08) {
    addSoft('MODERATE_DRIFT_AGAINST', 2.0, `Odds drifted +${driftAgainst.toFixed(2)} against this pick.`);
  }
  if (driftWith >= 0.04) {
    addBonus('SHARP_STEAM_WITH', 1.0, `Sharp market steamed -${driftWith.toFixed(2)} in favor of this pick.`);
  }
  if (simProb !== null && simProb < fairProb - 0.04) {
    addSoft(
      'SIM_DISAGREES_NEGATIVE',
      1.5,
      `Third-party simulation (${(simProb * 100).toFixed(1)}%) sits >4 pp below market fair (${(fairProb * 100).toFixed(1)}%).`
    );
  }

  // =========================================================================
  // 3. ASYMMETRIC FINAL SCORING & STATUS
  // =========================================================================
  const totalPenaltyPp = softFlags.reduce((acc, f) => acc + f.penaltyPp, 0);
  const rawBonusPp = bonuses.reduce((acc, b) => acc + b.bonusPp, 0);
  const cappedBonusPp = Math.min(rawBonusPp, MAX_POSITIVE_BONUS * 100);

  const adjProb = Math.max(
    0.05,
    Math.min(0.95, fairProb - totalPenaltyPp / 100 + cappedBonusPp / 100)
  );

  if (hardVetoes.length === 0) {
    if (totalPenaltyPp >= SOFT_PENALTY_VETO_THRESHOLD * 100) {
      addVeto(
        'CUMULATIVE_RISK_PENALTY',
        `Cumulative risk penalties (-${totalPenaltyPp.toFixed(1)} pp) exceed 4.5 pp safety limit.`
      );
    } else if (config.strictMode && softFlags.length >= 2) {
      addVeto(
        'MULTIPLE_RISK_FLAGS',
        `${softFlags.length} concurrent risk flags disqualify leg in strict mode.`
      );
    } else if (adjProb < config.minFairProb) {
      addVeto(
        'ADJ_PROB_BELOW_FLOOR',
        `Risk-adjusted probability (${(adjProb * 100).toFixed(1)}%) dropped below ${(config.minFairProb * 100).toFixed(0)}% floor.`
      );
    }
  }

  let status = 'CLEAN';
  if (hardVetoes.length > 0) {
    status = 'VETOED';
  } else if (softFlags.length > 0) {
    status = 'CAUTION';
  }

  let actualOutcome = null;
  if (match.actualScore && typeof match.actualScore.home === 'number' && typeof match.actualScore.away === 'number') {
    const totalGoals = match.actualScore.home + match.actualScore.away;
    const won = isOver ? totalGoals > line : totalGoals < line;
    actualOutcome = {
      score: `${match.actualScore.home}-${match.actualScore.away}`,
      totalGoals,
      won,
    };
  }

  return {
    matchId: match.id,
    espnEventId: match.espnEventId || null,
    espnLeague: match.espnLeague || null,
    kickoffIso: match.kickoffIso || null,
    matchLabel: match.label,
    kickoffEAT: match.kickoffEAT,
    league: match.league,
    tier: match.tier,
    line,
    lineKey,
    side,
    pickLabel: `${isOver ? 'Over' : 'Under'} ${lineKey}`,
    odds: +odds.toFixed(2),
    floorOdds,
    explicitSportyOdds: Boolean(explicitSportyOdds),
    vigPct: +dv.vigPct.toFixed(1),
    estimatedVig: dv.estimatedVig,
    fairProb: +fairProb.toFixed(4),
    simProb,
    impliedLambda,
    adjProb: +adjProb.toFixed(4),
    totalPenaltyPp: +totalPenaltyPp.toFixed(1),
    cappedBonusPp: +cappedBonusPp.toFixed(1),
    status,
    hardVetoes,
    softFlags,
    bonuses,
    keyDriver: summarizeKeyDriver(match, isOver, line, impliedLambda, combinedXgPg, combinedXgaPg, bonuses),
    failureRisk: summarizeFailureRisk(hardVetoes, softFlags, isOver, line),
    hasVerifiedXg: Boolean(combinedXgPg !== null || combinedXgaPg !== null),
    xgSampleMismatch: Boolean(h.xgMismatch || a.xgMismatch || h.xgaMismatch || a.xgaMismatch),
    metrics: {
      combinedXgPg: combinedXgPg !== null ? +combinedXgPg.toFixed(2) : null,
      combinedXgaPg: combinedXgaPg !== null ? +combinedXgaPg.toFixed(2) : null,
      homeAttDiff: h.attDiff !== null ? +h.attDiff.toFixed(1) : null,
      awayAttDiff: a.attDiff !== null ? +a.attDiff.toFixed(1) : null,
      homeDefLuck: h.defLuck !== null ? +h.defLuck.toFixed(1) : null,
      awayDefLuck: a.defLuck !== null ? +a.defLuck.toFixed(1) : null,
    },
    actualOutcome,
    _matchRef: match,
  };
}

/**
 * Evaluate every available half-goal Over/Under leg across all matches in a slate.
 */
export function evaluateSlate(slate, configInput = {}) {
  const config = { ...PRESETS.sniper, ...configInput };
  const allLegs = [];

  for (const match of slate.matches) {
    for (const lineKey of Object.keys(match.totals)) {
      for (const side of ['over', 'under']) {
        const res = evaluateLeg(match, lineKey, side, config);
        if (res) allLegs.push(res);
      }
    }
  }

  const rankOrder = { CLEAN: 0, CAUTION: 1, VETOED: 2 };
  allLegs.sort((a, b) => {
    if (rankOrder[a.status] !== rankOrder[b.status]) {
      return rankOrder[a.status] - rankOrder[b.status];
    }
    if (b.adjProb !== a.adjProb) return b.adjProb - a.adjProb;
    return a.vigPct - b.vigPct;
  });

  return {
    config,
    allLegs,
    cleanLegs: allLegs.filter((l) => l.status === 'CLEAN'),
    cautionLegs: allLegs.filter((l) => l.status === 'CAUTION'),
    vetoedLegs: allLegs.filter((l) => l.status === 'VETOED'),
  };
}