Files
Dreierpack-Manager/src/modern/content/statistics.cpp
T
MichaelandClaude Fable 5.2 8f607a9d89 A club analysis in the statistics: the season as charts; larger trophies
The engine counts the manager's club's running season from the almanac (read
"analysis"): matches, the points course beside the league's pace, records by venue,
what the first goal decided, goals by quarter of an hour, scorers and goal kinds. The
statistics open with it; the archive tables keep their place with larger type and
trophies.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-14 23:10:50 +01:00

1516 lines
88 KiB
C++

// SPDX-License-Identifier: GPL-3.0-only
#include "modern/content/statistics.hpp"
#include <algorithm>
#include <array>
#include <cstdio>
#include <map>
#include <set>
#include <string>
#include <variant>
#include <vector>
#include "formats/executable_layout.hpp"
#include "game/messages.hpp"
#include "game/schedule.hpp"
#include "game/table.hpp"
#include "modern/content/ui_contract.hpp"
#include "modern/content/world_package.hpp"
#include "modern/game/almanac.hpp"
namespace bmh::modern {
namespace {
using J = cli::Json;
using A = J::Array;
using O = J::Object;
J error(const char* code) { return O{{"ok", false}, {"error", code}}; }
std::string season_label(int start_year) {
const int next = (start_year + 1) % 100;
return std::to_string(start_year) + "/" + (next < 10 ? "0" : "") + std::to_string(next);
}
std::string iso_date(uint32_t counter, int display_start_year) {
const AlmanacDate d = almanac_date(counter, display_start_year);
char out[16];
std::snprintf(out, sizeof out, "%04d-%02d-%02d", d.year, d.month, d.day);
return out;
}
// Every season of the career: the finished ones decoded, then the running one.
std::vector<AlmanacSeason> seasons_of(const ModernState& g) {
std::vector<AlmanacSeason> out;
for (const auto& [name, bytes] : g.almanac.finished) out.push_back(decode_almanac_season(bytes));
if (g.almanac.current.season >= 0) out.push_back(g.almanac.current);
// Work on query copies only: finished season bytes and the loaded career
// remain immutable, including older saves affected by double-counted kicks.
for (auto& season : out)
for (auto& match : season.matches) modern::normalize_legacy_shootout(match);
return out;
}
// A competition as the statistics name it: leagues by the world's league id, cups by
// their cup id, the indoor Masters apart from the single tournaments.
struct Competition {
std::string id, name, type;
int order = 0; // leagues first (by index), then cups (by cup id)
};
std::string cup_name(const ModernState& g, int cup) {
// The indoor tournament's text names the venue of the next tournament (with a
// placeholder); the statistics list all tournaments under one name.
if (cup == 0xb) return "Hallenturnier";
std::string name;
try {
if (g.texts) name = almanac_utf8(message_text(g, ::bmh::layout::DeskState_FormatError_ExecutableField3 + uint32_t(cup + 1) * 4));
} catch (const std::exception&) {
name.clear();
}
return name.empty() ? "Pokal " + std::to_string(cup) : name;
}
Competition league_competition(const AlmanacSeason& s, int league) {
Competition c;
c.type = "league";
c.order = league;
for (const auto& l : s.leagues)
if (l.index == league) c.id = l.id, c.name = l.name;
if (c.id.empty()) c.id = "league:" + std::to_string(league);
if (c.name.empty()) c.name = "Liga " + std::to_string(league + 1);
return c;
}
Competition cup_competition(const ModernState& g, int cup, bool masters) {
Competition c;
c.type = "cup";
c.order = 100 + cup * 2 + (masters ? 1 : 0);
c.id = "cup:" + std::to_string(cup) + (masters ? ":masters" : "");
c.name = masters ? "Hallen-Masters" : cup_name(g, cup);
return c;
}
Competition competition_of(const ModernState& g, const AlmanacSeason& s, const AlmanacMatch& m) {
return m.type == 0 ? league_competition(s, m.league) : cup_competition(g, m.type - 1, false);
}
Competition competition_of(const ModernState& g, const AlmanacSeason& s, const AlmanacWinner& w) {
return w.type == 0 ? league_competition(s, w.league) : cup_competition(g, w.type - 1, w.detail == 1);
}
J club_json(const AlmanacSeason& s, uint16_t club) {
if (club >= s.clubs.size()) return nullptr;
return O{{"id", s.clubs[club].id}, {"name", s.clubs[club].name}};
}
std::string player_name(const AlmanacPlayer& p) { return p.first.empty() ? p.last : p.first + " " + p.last; }
const J* field(const J& request, const char* key) {
const auto* o = request.object();
if (!o) return nullptr;
const auto it = o->find(key);
return it == o->end() ? nullptr : &it->second;
}
J competitions(const ModernState& g, const std::vector<AlmanacSeason>& seasons) {
std::map<std::string, std::pair<Competition, std::vector<std::string>>> found; // id -> seasons
auto note = [&](const Competition& c, const std::string& season) {
auto& entry = found[c.id];
entry.first = c;
if (entry.second.empty() || entry.second.back() != season) entry.second.push_back(season);
};
for (const auto& s : seasons) {
const std::string label = season_label(s.start_year);
for (const auto& m : s.matches) note(competition_of(g, s, m), label);
for (const auto& w : s.winners) note(competition_of(g, s, w), label);
}
std::vector<std::pair<Competition, std::vector<std::string>>> list;
for (auto& [id, entry] : found) list.push_back(std::move(entry));
std::sort(list.begin(), list.end(), [](const auto& a, const auto& b) { return a.first.order < b.first.order; });
A out;
for (const auto& [c, labels] : list) {
A season_list;
for (const auto& l : labels) season_list.push_back(l);
out.push_back(O{{"id", c.id}, {"name", c.name}, {"type", c.type}, {"seasons", std::move(season_list)}});
}
return O{{"ok", true}, {"competitions", std::move(out)}};
}
J winners(const ModernState& g, const std::vector<AlmanacSeason>& seasons, const std::string& only) {
std::map<std::string, std::pair<Competition, A>> found;
for (const auto& s : seasons) {
std::map<std::string, int> edition; // several indoor tournaments in a season
for (const auto& w : s.winners) {
const Competition c = competition_of(g, s, w);
if (!only.empty() && c.id != only) continue;
auto& entry = found[c.id];
entry.first = c;
entry.second.push_back(O{{"season", season_label(s.start_year)}, {"year", s.start_year},
{"edition", ++edition[c.id]}, {"date", iso_date(w.date, s.display_start_year)},
{"winner", club_json(s, w.winner)},
{"runner_up", w.runner_up == 0xffff ? J(nullptr) : club_json(s, w.runner_up)}});
}
}
std::vector<std::pair<Competition, A>> list;
for (auto& [id, entry] : found) list.push_back(std::move(entry));
std::sort(list.begin(), list.end(), [](const auto& a, const auto& b) { return a.first.order < b.first.order; });
A out;
for (auto& [c, rows] : list)
out.push_back(O{{"id", c.id}, {"name", c.name}, {"type", c.type}, {"winners", std::move(rows)}});
return O{{"ok", true}, {"competitions", std::move(out)}};
}
struct PlayerRow {
std::string id, name, club_id, club_name;
int appearances = 0, goals = 0, assists = 0, yellow = 0, second_yellow = 0, red = 0;
uint64_t last = 0; // order of the player's last match (his club is the club of that match)
};
J player_stats(const ModernState& g, const std::vector<AlmanacSeason>& seasons, const std::string& competition,
const std::string& season, const std::string& sort, size_t limit, const std::string& team = {}) {
std::map<std::string, PlayerRow> rows;
uint64_t order = 0;
for (const auto& s : seasons) {
if (!season.empty() && season_label(s.start_year) != season) continue;
for (const auto& m : s.matches) {
++order;
if (competition_of(g, s, m).id != competition) continue;
auto row = [&](uint16_t player, int side) -> PlayerRow* {
if (player >= s.players.size() || side < 0 || side > 1) return nullptr;
const uint16_t club = side ? m.away : m.home;
if (!team.empty() && (club >= s.clubs.size() || s.clubs[club].id != team)) return nullptr;
const AlmanacPlayer& p = s.players[player];
PlayerRow& r = rows[p.id];
r.id = p.id, r.name = player_name(p);
if (order >= r.last) {
const uint16_t club = side ? m.away : m.home;
r.club_id = s.clubs.at(club).id, r.club_name = s.clubs.at(club).name, r.last = order;
}
return &r;
};
for (int side = 0; side < 2; ++side) {
const auto& lineup = m.lineup[size_t(side)];
for (size_t k = 0; k < std::min<size_t>(11, lineup.size()); ++k)
if (PlayerRow* r = row(lineup[k], side)) ++r->appearances;
}
for (const auto& e : m.events) {
switch (e.kind) {
case AlmanacEventKind::Goal:
if (PlayerRow* r = row(e.player, e.side)) ++r->goals;
if (PlayerRow* r = row(e.other, e.side)) ++r->assists;
break;
case AlmanacEventKind::YellowCard:
if (PlayerRow* r = row(e.player, e.side)) ++r->yellow;
break;
case AlmanacEventKind::SecondYellow:
if (PlayerRow* r = row(e.player, e.side)) ++r->second_yellow;
break;
case AlmanacEventKind::RedCard:
if (PlayerRow* r = row(e.player, e.side)) ++r->red;
break;
case AlmanacEventKind::Substitution:
if (PlayerRow* r = row(e.player, e.side)) ++r->appearances;
break;
default:
break;
}
}
}
}
auto key = [&](const PlayerRow& r) {
if (sort == "assists") return r.assists;
if (sort == "yellow") return r.yellow;
if (sort == "red") return r.red + r.second_yellow;
return r.goals;
};
std::vector<PlayerRow> list;
for (auto& [id, r] : rows)
if (key(r) > 0) list.push_back(std::move(r));
std::sort(list.begin(), list.end(), [&](const PlayerRow& a, const PlayerRow& b) {
if (key(a) != key(b)) return key(a) > key(b);
if (a.appearances != b.appearances) return a.appearances < b.appearances; // fewer games ranks first
return a.name < b.name;
});
A out;
int rank = 0, previous = -1;
for (size_t i = 0; i < list.size() && (limit == 0 || i < limit); ++i) {
const PlayerRow& r = list[i];
if (key(r) != previous) rank = int(i) + 1, previous = key(r);
out.push_back(O{{"rank", rank}, {"player", O{{"id", r.id}, {"name", r.name}}},
{"club", O{{"id", r.club_id}, {"name", r.club_name}}}, {"appearances", r.appearances},
{"goals", r.goals}, {"assists", r.assists}, {"yellow", r.yellow},
{"second_yellow", r.second_yellow}, {"red", r.red}});
}
return O{{"ok", true}, {"competition", competition}, {"season", season.empty() ? J(nullptr) : J(season)},
{"sort", sort}, {"players", std::move(out)}};
}
} // namespace
cli::Json query_statistics(const ModernState& g, const cli::Json& request) {
const J* kind = field(request, "kind");
if (!kind || !kind->string()) return error("invalid_statistics_request");
try {
const auto seasons = seasons_of(g);
if (*kind->string() == "competitions") return competitions(g, seasons);
if (*kind->string() == "winners") {
const J* only = field(request, "competition");
if (only && !only->string()) return error("invalid_statistics_request");
return winners(g, seasons, only ? *only->string() : std::string());
}
if (*kind->string() == "player_stats") {
const J* competition = field(request, "competition");
const J* season = field(request, "season");
const J* sort = field(request, "sort");
const J* limit = field(request, "limit");
if (!competition || !competition->string() || (season && !season->string() && !std::holds_alternative<std::nullptr_t>(season->value)) ||
(sort && !sort->string()) || (limit && (!limit->integer() || *limit->integer() < 0)))
return error("invalid_statistics_request");
const std::string order = sort ? *sort->string() : "goals";
if (order != "goals" && order != "assists" && order != "yellow" && order != "red")
return error("invalid_statistics_request");
return player_stats(g, seasons, *competition->string(), season && season->string() ? *season->string() : "",
order, limit ? size_t(*limit->integer()) : 50);
}
return error("invalid_statistics_request");
} catch (const std::exception&) {
return error("statistics_unavailable");
}
}
// --- the almanac view of the Modern UI (DataSource::read_almanac; the demo's request kinds) ------
namespace {
J almanac_person(const AlmanacSeason& s, uint16_t player) {
if (player == kAlmanacNone || player >= s.players.size()) return nullptr;
const AlmanacPlayer& p = s.players[player];
return O{{"id", p.id}, {"name", player_name(p)}};
}
J almanac_side(const ModernState& g, const AlmanacSeason& s, uint16_t club, int8_t manager) {
J m = nullptr;
if (manager >= 0 && size_t(manager) < s.managers.size()) {
const AlmanacManager& a = s.managers[size_t(manager)];
std::string id = a.index >= 0 && size_t(a.index) < g.manager_ids.size() ? g.manager_ids[size_t(a.index)] : std::string{};
if (id.empty()) id = "manager:slot-" + std::to_string(a.index);
m = O{{"id", id}, {"name", a.name}};
}
return O{{"id", s.clubs[club].id}, {"name", s.clubs[club].name}, {"crest", nullptr}, {"manager", std::move(m)}};
}
std::string match_id(const AlmanacSeason& s, size_t index) {
return "match:" + std::to_string(s.start_year) + "-" + std::to_string(index);
}
// One recorded match in the form the almanac screen reads. The score after 90 minutes and the
// extra time are told apart by the goal minutes; a line-up shorter than eleven is not known (null).
J almanac_match(const ModernState& g, const AlmanacSeason& s, size_t index) {
static constexpr const char* kKinds[8] = {"goal", "yellow", "red", "second_yellow", "injury", "substitution", "shootout", "miss"};
const AlmanacMatch& m = s.matches[index];
const Competition c = competition_of(g, s, m);
const std::string type = m.type == 0 ? "league" : m.type - 1 == 10 ? "friendly" : "cup";
int regulation[2] = {0, 0};
for (const auto& e : m.events)
if (e.kind == AlmanacEventKind::Goal && e.minute <= 90 && e.side < 2) ++regulation[e.side];
const bool shootout = m.decided == 2;
const bool indoor = m.type == 12 || m.type == 13; // indoor cup / masters: 2 x 20, then penalties
const bool extra = m.decided >= 1 && !indoor;
int goals[2] = {};
bool ambiguous_stoppage = false;
for (const auto& e : m.events) if (e.kind == AlmanacEventKind::Goal && e.side < 2) {
++goals[e.side];
// Both regular stoppage time and the first extra-time minutes use
// 91..93. F10 has no phase tag; do not invent a 90-minute score there.
if (e.minute > 90 && e.minute <= 93) ambiguous_stoppage = true;
}
const bool split_known = goals[0] == m.home_goals && goals[1] == m.away_goals && !ambiguous_stoppage;
J lineups = O{};
for (int side = 0; side < 2; ++side) {
const auto& l = m.lineup[size_t(side)];
if (l.size() < 11) {
std::get<O>(lineups.value)[side ? "away" : "home"] = nullptr;
continue;
}
A starters, bench;
for (size_t i = 0; i < l.size(); ++i) (i < 11 ? starters : bench).push_back(almanac_person(s, l[i]));
std::get<O>(lineups.value)[side ? "away" : "home"] = O{{"starters", std::move(starters)}, {"bench", std::move(bench)}};
}
A events;
for (const auto& e : m.events)
events.push_back(O{{"kind", kKinds[size_t(e.kind) & 7]}, {"minute", int(e.minute)}, {"side", e.side ? "away" : "home"},
{"player", almanac_person(s, e.player)}, {"other", almanac_person(s, e.other)}, {"detail", int(e.detail)}});
return O{{"id", match_id(s, index)}, {"date", iso_date(m.date, s.display_start_year)}, {"season", season_label(s.start_year)},
{"competition", O{{"id", c.id}, {"name", c.name}, {"type", type}}}, {"round", int(m.round)},
{"home", almanac_side(g, s, m.home, m.home_manager)}, {"away", almanac_side(g, s, m.away, m.away_manager)},
{"result", O{{"regulation", extra ? (split_known ? J(A{J(regulation[0]), J(regulation[1])}) : J(nullptr)) : J(A{J(int(m.home_goals)), J(int(m.away_goals))})},
{"extra", extra && split_known ? J(A{J(int(m.home_goals) - regulation[0]), J(int(m.away_goals) - regulation[1])}) : J(nullptr)},
{"penalties", shootout ? J(A{J(int(m.home_shootout)), J(int(m.away_shootout))}) : J(nullptr)},
{"final", A{J(int(m.home_goals)), J(int(m.away_goals))}}, {"extra_played", extra}, {"penalties_played", shootout}}},
{"referee", m.referee > 0 && m.referee < s.referees.size() ? J(s.referees[m.referee]) : J(nullptr)},
{"attendance", int64_t(m.attendance)},
{"weather", O{{"temperature", int(m.temperature)}, {"rain", int(m.rain)}}},
{"lineups", std::move(lineups)}, {"events", std::move(events)}};
}
} // namespace
cli::Json query_almanac(const ModernState& g, const cli::Json& request) {
const J* kind = field(request, "kind");
if (!kind || !kind->string()) return error("invalid_almanac_request");
try {
const auto seasons = seasons_of(g);
const std::string k = *kind->string();
if (k == "index") {
std::set<int> years;
std::string first, last;
size_t count = 0;
for (const auto& s : seasons)
for (const auto& m : s.matches) {
const std::string d = iso_date(m.date, s.display_start_year);
years.insert(std::stoi(d.substr(0, 4)));
if (first.empty() || d < first) first = d;
if (d > last) last = d;
++count;
}
A listed;
for (int y : years) listed.push_back(y);
return O{{"ok", true}, {"years", std::move(listed)}, {"match_count", int64_t(count)},
{"first_date", first.empty() ? J(nullptr) : J(first)}, {"last_date", last.empty() ? J(nullptr) : J(last)}};
}
if (k == "calendar") {
const J* year = field(request, "year");
if (!year || !year->integer()) return error("invalid_almanac_request");
std::map<std::string, std::pair<int, A>> days;
for (const auto& s : seasons)
for (size_t i = 0; i < s.matches.size(); ++i) {
const AlmanacMatch& m = s.matches[i];
const std::string d = iso_date(m.date, s.display_start_year);
if (std::stoi(d.substr(0, 4)) != *year->integer()) continue;
auto& day = days[d];
++day.first;
if (m.decided >= 1 || m.home_goals + m.away_goals >= 4) day.second.push_back(match_id(s, i));
}
A listed;
for (auto& [d, day] : days) listed.push_back(O{{"date", d}, {"count", day.first}, {"highlights", std::move(day.second)}});
return O{{"ok", true}, {"year", *year->integer()}, {"days", std::move(listed)}};
}
if (k == "day") {
const J* date = field(request, "date");
if (!date || !date->string()) return error("invalid_almanac_request");
A matches;
for (const auto& s : seasons)
for (size_t i = 0; i < s.matches.size(); ++i)
if (iso_date(s.matches[i].date, s.display_start_year) == *date->string()) matches.push_back(almanac_match(g, s, i));
return O{{"ok", true}, {"date", *date->string()}, {"matches", std::move(matches)}};
}
if (k == "match") {
const J* id = field(request, "id");
if (!id || !id->string()) return error("invalid_almanac_request");
for (const auto& s : seasons)
for (size_t i = 0; i < s.matches.size(); ++i)
if (match_id(s, i) == *id->string()) return O{{"ok", true}, {"match", almanac_match(g, s, i)}};
return error("almanac_match_not_found");
}
return error("invalid_almanac_request");
} catch (const std::exception&) {
return error("almanac_unavailable");
}
}
// --- the statistics screen of the Modern UI (DataSource::read_statistics; the demo's filters) ---
namespace {
constexpr const char* kSections[9] = {"Möglichkeiten", "Transferhistorie", "Analytics", "Ewige Tabelle", "WM-Statistiken",
"Saisonfinanzen", "Serien u. Rekorde", "Sieger", "Minuten-Statistik"};
constexpr const char* kWorldViews[6] = {"Sieger", "Gruppen", "Torschützen", "Finalrunde", "Tabelle", "Historie"};
// The first league of the countries with leagues, in the screen's order (de, es, it, fr, en);
// kEternal maps the eternal table's values (de, es, en, fr, it) to it.
struct Country { const char* code; const char* name; int league; };
constexpr Country kCountries[5] = {{"de", "Deutschland", 0}, {"es", "Spanien", 5}, {"it", "Italien", 8},
{"fr", "Frankreich", 7}, {"en", "England", 6}};
constexpr int kEternal[5] = {0, 1, 4, 3, 2};
J cell(const std::string& text) { return O{{"text", text}}; }
J numeric(int64_t v) { return O{{"text", std::to_string(v)}, {"value", v}}; }
J club_cell(const AlmanacClub& c) { return O{{"text", c.name}, {"club", c.id}}; }
J nation_cell(const AlmanacClub& c) { return O{{"text", c.name}, {"nation", c.id}}; }
// The world's nation of the league's clubs; without a world "nation:<code>".
std::string country_nation(const Country& c) {
if (const World* w = current_world())
for (const auto& l : w->leagues)
if (l.index == c.league && !l.members.empty())
if (const WorldClub* club = w->club(l.members.front()); club && !club->nation.empty()) return club->nation;
return std::string("nation:") + c.code;
}
void headings(O& out, std::initializer_list<const char*> names) {
A& cols = std::get<A>(out["columns"].value);
for (const char* n : names) cols.push_back(cell(n));
}
void row(O& out, A cells) { std::get<A>(out["rows"].value).push_back(O{{"cells", std::move(cells)}}); }
// The ids of a league's clubs as the running game has them.
std::set<std::string> league_club_ids(const ModernState& g, int league) {
std::set<std::string> ids;
if (league < 0) return ids;
const int first = league_first_team(league);
for (int t = first; t < first + int(kLeagueSizes[league]); ++t) {
const std::string id = t < int(g.world_club_id.size()) ? g.world_club_id[size_t(t)] : std::string{};
ids.insert(id.empty() ? "team:" + std::to_string(t) : id);
}
return ids;
}
void eternal_table(O& out, const std::vector<AlmanacSeason>& seasons, int league) {
headings(out, {"Verein", "Sp.", "S", "U", "N", "Punkte", "Tore"});
struct Sum { AlmanacClub club; int played = 0, won = 0, drawn = 0, lost = 0, points = 0, gf = 0, ga = 0; };
std::map<std::string, Sum> sums;
for (const auto& s : seasons)
for (const auto& t : s.tables) {
if (t.league != league) continue;
for (const auto& r : t.rows) {
Sum& x = sums[s.clubs[r.club].id];
x.club = s.clubs[r.club];
x.played += r.played, x.won += r.won, x.drawn += r.drawn, x.lost += r.lost, x.points += r.points;
x.gf += r.goals_for, x.ga += r.goals_against;
}
}
std::vector<Sum> list;
for (auto& [id, x] : sums) list.push_back(x);
std::stable_sort(list.begin(), list.end(), [](const Sum& a, const Sum& b) {
return a.points != b.points ? a.points > b.points : a.gf - a.ga > b.gf - b.ga;
});
for (const auto& x : list)
row(out, A{club_cell(x.club), numeric(x.played), numeric(x.won), numeric(x.drawn), numeric(x.lost), numeric(x.points),
cell(std::to_string(x.gf) + ":" + std::to_string(x.ga))});
}
// The national tournaments: cup 6 is the final round (a final), cup 7 the qualification.
bool national_match(const AlmanacMatch& m) { return m.type == 7 || m.type == 8; }
bool world_tournaments(O& out, const ModernState& g, const std::vector<AlmanacSeason>& seasons, int view) {
if (view == 0) {
headings(out, {"WM / EM", "Sieger", "Finalist", "Finale"});
for (auto s = seasons.rbegin(); s != seasons.rend(); ++s)
for (const auto& w : s->winners) {
if (w.type != 7) continue;
std::string final_score = "—";
for (const auto& m : s->matches)
if (m.type == 7 && ((m.home == w.winner && m.away == w.runner_up) || (m.away == w.winner && m.home == w.runner_up)))
final_score = std::to_string(m.home_goals) + ":" + std::to_string(m.away_goals);
const std::string when = std::to_string(s->start_year + 1);
row(out, A{J(O{{"text", cup_name(g, 6) + " " + when}, {"season", when}, {"winner", s->clubs[w.winner].id}}),
nation_cell(s->clubs[w.winner]), w.runner_up == 0xffff ? cell("—") : nation_cell(s->clubs[w.runner_up]),
cell(final_score)});
}
return true;
}
if (view == 2) {
headings(out, {"Spieler", "Land", "Tore"});
struct Scorer { int goals = 0; J player, nation; };
std::map<std::string, Scorer> scorers;
for (const auto& s : seasons)
for (const auto& m : s.matches) {
if (!national_match(m)) continue;
for (const auto& e : m.events) {
if (e.kind != AlmanacEventKind::Goal || e.player == kAlmanacNone || e.player >= s.players.size()) continue;
const AlmanacPlayer& p = s.players[e.player];
Scorer& x = scorers[p.id];
++x.goals;
x.player = O{{"text", player_name(p)}, {"player", p.id}};
x.nation = nation_cell(s.clubs[e.side ? m.away : m.home]);
}
}
std::vector<Scorer> list;
for (auto& [id, x] : scorers) list.push_back(x);
std::stable_sort(list.begin(), list.end(), [](const Scorer& a, const Scorer& b) { return a.goals > b.goals; });
for (size_t i = 0; i < list.size() && i < 20; ++i) row(out, A{list[i].player, list[i].nation, numeric(list[i].goals)});
return true;
}
if (view == 4 || view == 5) {
headings(out, {"Land", "Spiele", "Siege", "Punkte"});
struct Rec { AlmanacClub club; int games = 0, wins = 0, points = 0; };
std::map<std::string, Rec> recs;
for (const auto& s : seasons)
for (const auto& m : s.matches) {
if (!national_match(m)) continue;
for (int side = 0; side < 2; ++side) {
Rec& r = recs[s.clubs[side ? m.away : m.home].id];
r.club = s.clubs[side ? m.away : m.home];
const int own = side ? m.away_goals : m.home_goals, other = side ? m.home_goals : m.away_goals;
++r.games;
if (own > other) ++r.wins, r.points += 3;
else if (own == other) r.points += 1;
}
}
std::vector<Rec> list;
for (auto& [id, r] : recs) list.push_back(r);
std::stable_sort(list.begin(), list.end(), [](const Rec& a, const Rec& b) { return a.points > b.points; });
for (const auto& r : list) row(out, A{nation_cell(r.club), numeric(r.games), numeric(r.wins), numeric(r.points)});
return true;
}
return false; // groups, final round: not yet
}
void series_and_records(O& out, const ModernState& g, const std::vector<AlmanacSeason>& seasons, int league) {
headings(out, {"Serie / Rekord", "Verein", "Wert"});
const auto ids = league_club_ids(g, league);
struct Run { int unbeaten = 0, wins = 0, scoring = 0, best_unbeaten = 0, best_wins = 0, best_scoring = 0; AlmanacClub club; };
std::map<std::string, Run> runs;
struct Best { AlmanacClub club; std::array<int, 3> value{}; }; // home wins, away wins, goals in one season
std::map<std::string, Best> season_best;
int biggest = -1, crowd = -1;
J biggest_club = cell("—"), crowd_club = cell("—");
std::string big_score;
for (const auto& s : seasons) {
std::map<std::string, Best> this_season;
for (const auto& m : s.matches) {
if (m.type != 0 || m.league != league) continue;
for (int side = 0; side < 2; ++side) {
const AlmanacClub& c = s.clubs[side ? m.away : m.home];
if (!ids.count(c.id)) continue;
const int own = side ? m.away_goals : m.home_goals, other = side ? m.home_goals : m.away_goals;
Run& r = runs[c.id];
r.club = c;
r.unbeaten = own >= other ? r.unbeaten + 1 : 0;
r.wins = own > other ? r.wins + 1 : 0;
r.scoring = own > 0 ? r.scoring + 1 : 0;
r.best_unbeaten = std::max(r.best_unbeaten, r.unbeaten);
r.best_wins = std::max(r.best_wins, r.wins);
r.best_scoring = std::max(r.best_scoring, r.scoring);
Best& x = this_season[c.id];
x.club = c;
if (own > other) ++x.value[size_t(side)];
x.value[2] += own;
if (own - other > biggest) biggest = own - other, biggest_club = club_cell(c), big_score = std::to_string(own) + " : " + std::to_string(other);
if (side == 0 && int(m.attendance) > crowd) crowd = int(m.attendance), crowd_club = club_cell(c);
}
}
for (auto& [id, x] : this_season) {
Best& b = season_best[id];
b.club = x.club;
for (size_t k = 0; k < 3; ++k) b.value[k] = std::max(b.value[k], x.value[k]);
}
}
const auto best_run = [&](int Run::*value, const char* name) {
int best = 0;
J who = cell("—");
for (const auto& [id, r] : runs) if (r.*value > best) best = r.*value, who = club_cell(r.club);
if (best > 0) row(out, A{cell(name), who, numeric(best)});
};
const auto best_season = [&](size_t k, const char* name) {
int best = 0;
J who = cell("—");
for (const auto& [id, b] : season_best) if (b.value[k] > best) best = b.value[k], who = club_cell(b.club);
if (best > 0) row(out, A{cell(name), who, numeric(best)});
};
best_run(&Run::best_unbeaten, "Ungeschlagen");
best_run(&Run::best_wins, "Siege in Folge");
best_season(0, "Heimsiege");
best_season(1, "Auswärtssiege");
best_season(2, "Tore in einer Saison");
if (biggest > 0) row(out, A{cell("Höchster Sieg"), biggest_club, cell(big_score)});
best_run(&Run::best_scoring, "Längste Torserie");
if (crowd > 0) row(out, A{cell("Meiste Zuschauer"), crowd_club, numeric(crowd)});
}
void winners_by_season(O& out, const std::vector<AlmanacSeason>& seasons, int category, int country) {
struct Title { const char* text; const char* trophy; int type; int league; int detail; };
std::vector<Title> titles;
if (category == 0) {
const Country& c = kCountries[country];
static constexpr const char* trophies[]{"championship","es-la-liga","it-serie-a","fr-ligue-1","en-premier-league"};
titles.push_back({"Meisterschaft", trophies[country], 0, c.league, 0});
if (c.league == 0) {
titles.push_back({"DFB-Pokal", "dfb-cup", 1, -1, 0});
titles.push_back({"Supercup", "supercup", 9, -1, 0}); // cup-table index 8 + 1
}
out["note"] = std::string(c.name) + " · Titelträger im Saisonvergleich";
} else if (category == 1) {
// Almanac types are cup-table index + 1: UEFA=1, Champions=2, Winners=3.
titles = {{"Champions League", "champions-league", 3, -1, 0}, {"Pokalsieger", "cup-winners", 4, -1, 0}, {"UEFA-Cup", "uefa-cup", 2, -1, 0}};
out["note"] = "Europäische Titelträger im Saisonvergleich";
} else {
titles = {{"Sieger", "indoor-masters", 12, -1, 1}, {"Finalist", "", 12, -1, 2}};
out["note"] = "Hallenmasters · Sieger und Finalisten";
}
headings(out, {"Saison"});
for (const auto& t : titles) std::get<A>(out["columns"].value).push_back(O{{"text", t.text}, {"trophy", t.trophy}});
for (auto s = seasons.rbegin(); s != seasons.rend(); ++s) {
A cells{cell(season_label(s->start_year))};
bool any = false;
for (const auto& t : titles) {
J value = cell("—");
for (const auto& w : s->winners) {
if (w.type != t.type || (t.type == 0 && w.league != t.league)) continue;
if (t.detail >= 1 && w.detail != 1) continue;
const uint16_t c = t.detail == 2 ? w.runner_up : w.winner;
if (c != 0xffff) value = club_cell(s->clubs[c]), any = true;
}
cells.push_back(std::move(value));
}
if (any) row(out, std::move(cells));
}
}
void minute_buckets(O& out, const std::vector<AlmanacSeason>& seasons, const std::string& own) {
headings(out, {"Ereignis"});
for (int i = 0; i < 18; ++i) std::get<A>(out["columns"].value).push_back(cell(std::to_string(i * 5) + "."));
std::array<std::array<int, 18>, 4> counts{};
for (const auto& s : seasons)
for (const auto& m : s.matches) {
const int side = s.clubs[m.home].id == own ? 0 : s.clubs[m.away].id == own ? 1 : -1;
if (side < 0) continue;
for (const auto& e : m.events) {
if (e.side != side || e.minute < 1 || e.minute > 90) continue;
const size_t b = size_t(std::min(17, (e.minute - 1) / 5));
if (e.kind == AlmanacEventKind::Goal) ++counts[0][b], ++counts[1][b];
if (e.kind == AlmanacEventKind::Miss) ++counts[1][b];
if (e.kind == AlmanacEventKind::YellowCard) ++counts[2][b];
if (e.kind == AlmanacEventKind::RedCard || e.kind == AlmanacEventKind::SecondYellow) ++counts[3][b];
}
}
const char* names[4] = {"Tore", "Chancen", "Gelb", "Rot"};
for (size_t k = 0; k < 4; ++k) {
A cells{cell(names[k])};
for (size_t b = 0; b < 18; ++b) cells.push_back(numeric(counts[k][b]));
row(out, std::move(cells));
}
}
} // namespace
cli::Json query_statistics_screen(const ModernState& g, int manager, const cli::Json& request) {
const auto reject = [](const char* e) { return J(O{{"ok", false}, {"fictional", false}, {"error", e}}); };
const auto* o = request.object();
if (!o) return reject("invalid_statistics_request");
for (const auto& [key, value] : *o)
if (key != "section" && key != "category" && key != "country" && key != "winner_country" && key != "absolute" && key != "curves")
return reject("unknown_statistics_filter");
const auto integer = [&](const char* key, int fallback, int maximum) -> int {
const J* v = field(request, key);
if (!v) return fallback;
return v->integer() && *v->integer() >= 0 && *v->integer() <= maximum ? int(*v->integer()) : -1;
};
const int section = integer("section", 7, 8), category = integer("category", 0, 5), country = integer("country", 0, 5);
if (section < 0 || category < 0 || country < 0 || (category != 0 && category != 1 && category != 5))
return reject("invalid_statistics_filter");
std::string winner_country = country_nation(kCountries[0]);
if (const J* w = field(request, "winner_country")) {
if (!w->string()) return reject("invalid_statistics_country");
winner_country = *w->string();
}
int winner_index = -1;
for (int i = 0; i < 5; ++i)
if (country_nation(kCountries[i]) == winner_country) winner_index = i;
if (winner_index < 0) return reject("invalid_statistics_country");
const J* abs = field(request, "absolute");
const bool absolute = abs && std::holds_alternative<bool>(abs->value) && std::get<bool>(abs->value);
A curves;
for (int i = 0; i < 6; ++i) curves.push_back(true);
if (const J* c = field(request, "curves")) {
if (!c->array() || c->array()->size() != 6) return reject("invalid_statistics_curves");
curves = *c->array();
}
try {
const auto seasons = seasons_of(g);
const int team = manager >= 0 && size_t(manager) < g.manager_teams.size() ? g.manager_teams[size_t(manager)] : -1;
const bool club = team >= 0 && team < league_clubs();
std::string own_id;
if (club) {
own_id = team < int(g.world_club_id.size()) ? g.world_club_id[size_t(team)] : std::string{};
if (own_id.empty()) own_id = "team:" + std::to_string(team);
}
const int own_league = club ? team_league(team) : -1;
const int year = g.display_start_year + g.season;
std::string manager_name;
const size_t at = size_t(std::max(0, manager)) * 0xb0c + 0xa8;
for (size_t i = 0; i < 30 && at + i < g.manager_records.size() && g.manager_records[at + i]; ++i)
manager_name.push_back(char(g.manager_records[at + i]));
A sections, views, countries, eternal;
for (const char* s : kSections) sections.push_back(s);
for (const char* v : kWorldViews) views.push_back(v);
for (const auto& c : kCountries) countries.push_back(O{{"id", country_nation(c)}, {"name", c.name}});
for (int v = 0; v < 5; ++v)
eternal.push_back(O{{"value", v}, {"nation", country_nation(kCountries[kEternal[v]])}, {"name", kCountries[kEternal[v]].name}});
eternal.push_back(O{{"value", 5}, {"name", "Absolut"}});
O out{{"ok", true}, {"fictional", false}, {"available", true}, {"section", section}, {"category", category},
{"country", country}, {"winner_country", winner_country}, {"absolute", absolute}, {"curves", curves},
{"title", kSections[section]}, {"season", season_label(year)}, {"previous_season", season_label(year - 1)},
{"year", year}, {"manager", g.manager_presentation(manager) ? g.manager_presentation(manager)->name : manager_name.empty() ? "—" : almanac_utf8(manager_name)},
{"club", club ? J(own_id) : J(nullptr)}, {"columns", A{}}, {"rows", A{}}, {"countries", std::move(countries)},
{"sections", std::move(sections)}, {"world_views", std::move(views)}, {"series", A{}},
{"eternal_countries", std::move(eternal)}};
// the views without a record of their own yet: title chances, transfers, weekly curves,
// season finances; the groups and final round of the national tournaments
bool known = true;
if (section == 3) {
eternal_table(out, seasons, country == 5 ? own_league : kCountries[kEternal[country]].league);
} else if (section == 4) {
known = world_tournaments(out, g, seasons, country);
} else if (section == 6) {
if (club) series_and_records(out, g, seasons, own_league);
} else if (section == 7) {
winners_by_season(out, seasons, category, winner_index);
} else if (section == 8) {
if (club) minute_buckets(out, seasons, own_id);
} else {
known = false;
}
if (!known) out["reason"] = "not_recorded";
out["available"] = known && !std::get<A>(out["rows"].value).empty();
return J(std::move(out));
} catch (const std::exception&) {
return reject("statistics_unavailable");
}
}
// Current-season views for the existing player-statistics and fair-play presenters.
cli::Json query_rankings(const ModernState& g, int manager, const cli::Json& request) {
const J* kind = field(request, "kind"), *wanted = field(request, "leagueId"), *scope_value = field(request, "scope");
if (!kind || !kind->string()) return error("invalid_rankings_request");
const bool fair = *kind->string() == "fairplay";
if (!fair && *kind->string() != "player-rankings") return error("invalid_rankings_request");
if ((scope_value && (!scope_value->integer() || *scope_value->integer() < 0 || *scope_value->integer() > 1)) || manager < 0 || size_t(manager) >= g.manager_teams.size()) return error("invalid_rankings_request");
const int scope = scope_value ? int(*scope_value->integer()) : 0;
const int own = g.manager_teams[size_t(manager)];
if (own < 0 || own >= league_clubs()) return error("no_club");
const auto league_id = [&](int l) { return size_t(l) < g.world_league_id.size() && !g.world_league_id[size_t(l)].empty() ? g.world_league_id[size_t(l)] : "league:" + std::to_string(l); };
int requested = -1;
for (int l = 0; l < kLeagueCount; ++l) if (wanted && wanted->string() && *wanted->string() == league_id(l)) requested = l;
if (!fair && requested < 0) return error("invalid_rankings_league");
const int league = fair ? 0 : scope ? team_league(own) : requested;
const std::string season = season_label(g.display_start_year + g.season);
const auto team_id = [&](int t) {return size_t(t) < g.world_club_id.size() && !g.world_club_id[size_t(t)].empty() ? g.world_club_id[size_t(t)] : "team:" + std::to_string(t);};
const auto team_name = [&](int t) {return size_t(t) < g.world_club_name.size() && !g.world_club_name[size_t(t)].empty() ? g.world_club_name[size_t(t)] : almanac_utf8(g.club_name(t));};
try {
const auto seasons = seasons_of(g);
O out{{"ok", true}, {"kind", fair ? "fairplay" : "player-rankings"}, {"leagueId", league_id(league)}, {"season", season}, {"team", O{{"id", team_id(own)}, {"name", team_name(own)}}}};
if (!fair) {
out["requestLeagueId"] = league_id(requested); out["scope"] = scope;
std::map<std::string, int> current_teams;
for (int t = 0; t < league_clubs(); ++t) {
const auto range = squad_range(t);
for (size_t slot = range.first; slot < range.first + range.count && slot < g.squad_slots.size(); ++slot) {
const size_t player = g.squad_slots[slot] & 0x0fff;
if (player != 0x0fff && player < g.world_player_id.size() && !g.world_player_id[player].empty()) current_teams[g.world_player_id[player]] = t;
}
}
A categories;
for (const char* sort : {"goals", "assists", "yellow", "red"}) {
J stats = player_stats(g, seasons, league_id(league), season, sort, 0, scope ? team_id(own) : std::string());
for (auto& row : std::get<A>(stats.object()->at("players").value)) {
auto& values = *row.object(); const auto& pid = *values.at("player").object()->at("id").string();
const World* world = current_world(); const WorldPlayer* player = world ? world->player(pid) : nullptr;
values["photoAssetId"] = player && !player->photo.empty() ? J(player->photo) : J(nullptr);
const auto active = current_teams.find(pid);
values["currentTeam"] = active == current_teams.end() ? J(nullptr) : J(O{{"id", team_id(active->second)}, {"name", team_name(active->second)}});
values["value"] = std::string(sort) == "red" ? J(*values.at("red").integer() + *values.at("second_yellow").integer()) : values.at(std::string(sort));
}
categories.push_back(std::move(stats.object()->at("players")));
}
out["categories"] = std::move(categories);
} else {
// A presentation weighting, matching the approved UI; it does not affect discipline.
out["weights"] = O{{"yellow", 1}, {"red", 4}};
struct Cards { std::string id, name; int yellow = 0, red = 0; };
std::vector<Cards> cards;
for (int t = league_first_team(league); t < league_first_team(league) + kLeagueSizes[league]; ++t) cards.push_back({team_id(t), team_name(t)});
int matches = 0;
for (const auto& s : seasons) if (season_label(s.start_year) == season)
for (const auto& m : s.matches) {
if (competition_of(g, s, m).id != league_id(league)) continue;
++matches;
for (const auto& e : m.events) {
if (e.side > 1) continue;
const auto club = club_json(s, e.side ? m.away : m.home);
if (!club.object()) continue;
const auto& id = *club.object()->at("id").string();
for (auto& c : cards) if (c.id == id) {
if (e.kind == AlmanacEventKind::YellowCard) ++c.yellow;
if (e.kind == AlmanacEventKind::RedCard || e.kind == AlmanacEventKind::SecondYellow) ++c.red;
}
}
}
std::stable_sort(cards.begin(), cards.end(), [](const Cards& a, const Cards& b) {return a.yellow + 4 * a.red < b.yellow + 4 * b.red;});
A rows;
for (const auto& c : cards) rows.push_back(O{{"rank", int(rows.size() + 1)}, {"team", O{{"id", c.id}, {"name", c.name}}}, {"yellow", c.yellow}, {"red", c.red}, {"points", c.yellow + 4 * c.red}});
out["rows"] = std::move(rows); out["recordedMatches"] = matches;
}
return out;
} catch (const std::exception&) { return error("rankings_unavailable"); }
}
// --- the live ticker of the Modern UI: the recorded matches of the last kickoff ---------------
// The ticker's wording of one event. The sentence is picked from a few variants by the
// event's own facts (minute, side, kind), so the same match always reads the same and no
// random number of the game is drawn. `home`/`away` is the score after the event.
std::pair<std::string, std::string> ticker_phrase(int kind, const std::string& team, const std::string& who,
const std::string& other, int detail, int minute, int home, int away,
bool away_side) {
const std::string score = std::to_string(home) + ":" + std::to_string(away);
const std::string player = who.empty() ? team : who;
const auto pick = [&](std::initializer_list<const char*> variants) {
const size_t n = variants.size();
uint32_t hash = 2166136261u; // FNV-1a over the player's name, the minute, the kind and the side
for (unsigned char c : player) hash = (hash ^ c) * 16777619u;
for (unsigned v : {unsigned(minute), unsigned(kind), away_side ? 1u : 0u}) hash = (hash ^ v) * 16777619u;
const size_t at = size_t(hash >> 7) % n;
return std::string(*(variants.begin() + at));
};
const auto fill = [&](std::string text) {
for (const auto& [key, value] : {std::pair<const char*, const std::string&>{"%p", player}, {"%t", team}, {"%s", score}, {"%o", other}})
for (size_t at = text.find(key); at != std::string::npos; at = text.find(key, at + value.size())) text.replace(at, 2, value);
return text;
};
switch (AlmanacEventKind(kind)) {
case AlmanacEventKind::Goal: {
const int own = away_side ? away : home, theirs = away_side ? home : away;
std::string headline = own == theirs ? "Ausgleich für " + team
: own == theirs + 1 ? "Führung für " + team
: own > theirs + 2 ? team + " zieht davon"
: own == theirs - 1 ? "Anschlusstreffer für " + team
: "Tor für " + team;
std::string body = detail == 1 ? pick({"%p verwandelt den ruhenden Ball zum %s.", "%p trifft nach einem Standard zum %s."})
: detail == 2 ? pick({"%p staubt zum %s ab.", "%p ist beim Nachschuss zur Stelle: %s."})
: detail == 3 ? pick({"%p trifft nach einer Ecke zum %s.", "Ecke, Abschluss, Tor: %p erzielt das %s."})
: pick({"%p trifft zum %s.", "%p vollendet zum %s.", "%p lässt dem Torwart keine Chance: %s.",
"%p schließt zum %s ab."});
if (!other.empty()) body += pick({" Vorlage: %o.", " %o hatte aufgelegt.", " Die Vorarbeit kam von %o."});
if (minute >= 88 && own == theirs + 1) body += " Ein später Treffer.";
return {headline, fill(body)};
}
case AlmanacEventKind::Miss:
return {"Chance für " + team,
fill(detail == 1 ? pick({"%p vergibt den Standard.", "%p setzt den ruhenden Ball neben das Tor."})
: detail == 3 ? pick({"Nach einer Ecke kommt %p zum Abschluss, ohne Erfolg.", "%p köpft nach der Ecke vorbei."})
: pick({"%p vergibt.", "%p scheitert am Torwart.", "%p zielt zu ungenau.", "%p bringt den Ball nicht im Tor unter."}))};
case AlmanacEventKind::YellowCard:
return {"Gelbe Karte", fill(pick({"%p (%t) sieht Gelb.", "Gelb für %p (%t).", "%p (%t) wird verwarnt."}))};
case AlmanacEventKind::SecondYellow:
return {"Gelb-Rot", fill(pick({"%p (%t) sieht Gelb-Rot und muss vom Platz.", "Zweite Verwarnung für %p: %t spielt in Unterzahl weiter."}))};
case AlmanacEventKind::RedCard:
return {"Rote Karte", fill(pick({"%p (%t) sieht Rot.", "Platzverweis für %p: %t spielt in Unterzahl weiter."}))};
case AlmanacEventKind::Injury:
return {"Verletzung", fill(pick({"%p (%t) muss behandelt werden.", "%p (%t) bleibt verletzt liegen."}))};
case AlmanacEventKind::Substitution:
return {"Wechsel bei " + team,
fill(other.empty() ? "%p kommt ins Spiel." : pick({"%p kommt für %o.", "%o geht, %p kommt.", "%p ersetzt %o."}))};
case AlmanacEventKind::ShootoutKick:
return {"Elfmeterschießen", fill(detail ? pick({"%p verwandelt.", "%p trifft sicher."}) : pick({"%p verschießt.", "%p scheitert."}))};
}
return {"", ""};
}
namespace {
// The ticker's lines for an event of the almanac (German, as the interface's demo).
std::pair<std::string, std::string> ticker_text(const AlmanacSeason& s, const AlmanacMatch& m, const AlmanacEvent& e,
int home, int away) {
const std::string team = s.clubs[e.side ? m.away : m.home].name;
const std::string who = e.player != kAlmanacNone && e.player < s.players.size() ? player_name(s.players[e.player]) : std::string{};
const std::string other = e.other != kAlmanacNone && e.other < s.players.size() ? player_name(s.players[e.other]) : std::string{};
return ticker_phrase(int(e.kind), team, who, other, e.detail, e.minute, home, away, e.side != 0);
}
const char* event_kind(AlmanacEventKind k) {
static constexpr const char* kKinds[8] = {"goal", "yellow", "red", "second_yellow", "injury", "substitution", "shootout", "miss"};
return kKinds[size_t(k) & 7];
}
} // namespace
cli::Json live_league_table(const ModernState& g, int league, int round, const std::vector<LiveGame>& games) {
LeagueTable base;
if (round > 1) base = compute_league_table(g, league, 0, round - 1, 7, 1);
else base.league = league, base.size = int(kLeagueSizes[league]);
const int first = league_first_team(league);
LeagueTable t = base;
for (const LiveGame& game : games) {
const int club[2] = {game.home - first, game.away - first};
if (club[0] < 0 || club[0] >= t.size || club[1] < 0 || club[1] >= t.size) continue;
const uint8_t goals[2] = {uint8_t(game.home_goals), uint8_t(game.away_goals)};
add_result(t, club, goals, 3, 1);
}
sort_table(t, 0);
std::vector<int> order(size_t(t.size));
for (int i = 0; i < t.size; ++i) order[size_t(i)] = i;
std::stable_sort(order.begin(), order.end(), [&](int a, int b) { return t.rank(a) < t.rank(b); });
A rows;
for (int i : order) {
const int played = t.games(i), won = t.wins[size_t(i)], lost = t.defeats[size_t(i)];
std::string name = size_t(first + i) < g.world_club_name.size() ? g.world_club_name[size_t(first + i)] : std::string{};
if (name.empty()) name = almanac_utf8(g.club_name(first + i));
rows.push_back(O{{"rank", t.rank(i) + 1}, {"previousRank", round > 1 ? J(base.rank(i) + 1) : J(nullptr)},
{"team", O{{"id", ui_team_id(g, first + i)}, {"name", name}}}, {"played", played}, {"won", won},
{"drawn", std::max(0, played - won - lost)}, {"lost", lost}, {"goalsFor", int(t.goals_for[size_t(i)])},
{"goalsAgainst", int(t.goals_against[size_t(i)])}, {"points", int(t.points[size_t(i)])}});
}
const Competition c = league_competition(g.almanac.current, league);
return O{{"competitionId", c.id}, {"name", c.name}, {"round", round}, {"rows", std::move(rows)}};
}
cli::Json live_fixture(const ModernState& g, uint32_t after_date, uint32_t until_date, uint64_t revision) {
// the matches of the last kickoff (dates after_date <= d < until_date) from the almanac: the
// ones with a human manager are the ticker's matches (at most four), all others the conference
struct Ref { const AlmanacSeason* season; size_t index; };
const auto seasons = seasons_of(g);
std::vector<Ref> human, others;
for (const auto& s : seasons)
for (size_t i = 0; i < s.matches.size(); ++i) {
const AlmanacMatch& m = s.matches[i];
if (m.date < after_date || m.date > until_date) continue; // played from the desk day on (only played matches are recorded)
((m.home_manager >= 0 || m.away_manager >= 0) && human.size() < 4 ? human : others).push_back({&s, i});
}
if (human.empty()) return O{{"ok", false}, {"error", "live_no_human_match"}};
A owners, matches, conference;
std::map<std::string, std::string> owner_match;
for (const Ref& r : human) {
const AlmanacSeason& s = *r.season;
const AlmanacMatch& m = s.matches[r.index];
const std::string id = match_id(s, r.index);
A match_owners;
for (int side = 0; side < 2; ++side) {
const int8_t mi = side ? m.away_manager : m.home_manager;
if (mi < 0 || size_t(mi) >= s.managers.size()) continue;
const AlmanacManager& a = s.managers[size_t(mi)];
std::string mid = a.index >= 0 && size_t(a.index) < g.manager_ids.size() ? g.manager_ids[size_t(a.index)] : std::string{};
if (mid.empty()) mid = "manager:slot-" + std::to_string(a.index);
if (owner_match.count(mid)) continue;
owner_match[mid] = id;
match_owners.push_back(mid);
const AlmanacClub& c = s.clubs[side ? m.away : m.home];
const size_t rec = size_t(std::max(0, a.index)) * 0xb0c + 0x221;
owners.push_back(O{{"id", mid}, {"portrait", rec < g.manager_records.size() ? int(g.manager_records[rec]) : 0},
{"name", a.name}, {"team", O{{"id", c.id}, {"name", c.name}, {"role", c.id.starts_with("nt:") ? "national" : "club"}}},
{"match_id", id}, {"view", nullptr}});
}
const Competition c = competition_of(g, s, m);
matches.push_back(O{{"id", id}, {"home", O{{"id", s.clubs[m.home].id}, {"name", s.clubs[m.home].name}}},
{"away", O{{"id", s.clubs[m.away].id}, {"name", s.clubs[m.away].name}}},
{"owners", std::move(match_owners)}, {"competition", c.name},
// known before the kickoff (frame 0 on): the crowd and the weather (rain is the
// original's weather picture 0-7); the indoor tournament has no weather
{"attendance", int64_t(m.attendance)},
{"weather", m.type - 1 == 0xb ? J(nullptr) : J(O{{"temperature", int(m.temperature)}, {"rain", int(m.rain)}})}});
}
for (const Ref& r : others) conference.push_back(almanac_match(g, *r.season, r.index));
// the frames: kickoff, every event of a ticker match in minute order, half time, the end
struct Moment { int minute; int order; const Ref* ref; const AlmanacEvent* event; const char* phase; };
std::vector<Moment> moments;
bool extra = false, shootout = false;
for (const Ref& r : human) {
const AlmanacMatch& m = r.season->matches[r.index];
extra |= m.decided >= 1, shootout |= m.decided == 2;
for (const auto& e : m.events) moments.push_back({e.minute, 1, &r, &e, nullptr});
}
moments.push_back({0, 0, nullptr, nullptr, "kickoff"});
moments.push_back({45, 2, nullptr, nullptr, "interval"});
moments.push_back({46, 0, nullptr, nullptr, "restart"});
moments.push_back({extra ? 120 : 90, 3, nullptr, nullptr, shootout ? "shootout_end" : "fulltime"});
std::stable_sort(moments.begin(), moments.end(), [](const Moment& a, const Moment& b) {
return a.minute != b.minute ? a.minute < b.minute : a.order < b.order;
});
// the live tables: per league of a ticker match, the table before its matchday plus every
// match of that round in this kickoff with its score at the frame's minute (the final
// whistle uses the recorded result). A frame carries a league's table when it changed
// there (all of them on the first frame).
struct LiveLeague {
int league = 0, round = 0;
std::vector<const AlmanacMatch*> games;
std::vector<std::array<int, 2>> teams; // runtime teams of each game
std::string last; // the scores the table was last built from
};
std::vector<LiveLeague> live_leagues;
for (const Ref& r : human) {
const AlmanacMatch& m = r.season->matches[r.index];
if (m.type != 0 || m.league >= kLeagueCount || m.round == 0) continue;
if (std::any_of(live_leagues.begin(), live_leagues.end(), [&](const LiveLeague& l) { return l.league == m.league; })) continue;
LiveLeague l;
l.league = m.league, l.round = m.round;
const int first = league_first_team(m.league);
std::map<std::string, int> team;
for (int t = first; t < first + int(kLeagueSizes[m.league]); ++t) team[ui_team_id(g, t)] = t;
for (const std::vector<Ref>* list : {&human, &others})
for (const Ref& o : *list) {
const AlmanacMatch& x = o.season->matches[o.index];
if (x.type != 0 || x.league != m.league || x.round != m.round) continue;
const auto h = team.find(o.season->clubs[x.home].id), a = team.find(o.season->clubs[x.away].id);
if (h == team.end() || a == team.end()) continue;
l.games.push_back(&x);
l.teams.push_back({h->second, a->second});
}
live_leagues.push_back(std::move(l));
}
const auto live_table = [&](LiveLeague& l, int minute, bool final_whistle) -> J {
std::vector<LiveGame> games;
std::string key;
for (size_t k = 0; k < l.games.size(); ++k) {
const AlmanacMatch& x = *l.games[k];
LiveGame game{l.teams[k][0], l.teams[k][1], 0, 0};
if (final_whistle) game.home_goals = x.home_goals, game.away_goals = x.away_goals;
else
for (const auto& e : x.events)
if (e.kind == AlmanacEventKind::Goal && e.minute <= minute) ++(e.side ? game.away_goals : game.home_goals);
if (minute > 0) games.push_back(game);
key += std::to_string(game.home_goals) + ":" + std::to_string(game.away_goals) + ",";
}
if (key == l.last) return nullptr;
l.last = key;
return live_league_table(g, l.league, l.round, games);
};
struct Tally { int score[2] = {0, 0}, chances[2] = {0, 0}, yellow[2] = {0, 0}, red[2] = {0, 0}, shootout[2] = {0, 0}; };
std::vector<Tally> tally(human.size());
A frames, events;
for (const Moment& mo : moments) {
if (mo.event) {
const size_t k = size_t(mo.ref - human.data());
const AlmanacSeason& s = *mo.ref->season;
const AlmanacMatch& m = s.matches[mo.ref->index];
const AlmanacEvent& e = *mo.event;
Tally& t = tally[k];
const size_t side = e.side ? 1 : 0;
if (e.kind == AlmanacEventKind::Goal) ++t.score[side], ++t.chances[side];
if (e.kind == AlmanacEventKind::Miss) ++t.chances[side];
if (e.kind == AlmanacEventKind::YellowCard) ++t.yellow[side];
if (e.kind == AlmanacEventKind::RedCard || e.kind == AlmanacEventKind::SecondYellow) ++t.red[side];
if (e.kind == AlmanacEventKind::ShootoutKick && e.detail) ++t.shootout[side];
const auto [headline, body] = ticker_text(s, m, e, t.score[0], t.score[1]);
const std::string mid = match_id(s, mo.ref->index);
events.push_back(O{{"id", mid + ":event:" + std::to_string(events.size())}, {"sequence", int64_t(frames.size())},
{"match_id", mid}, {"minute", mo.minute}, {"kind", event_kind(e.kind)}, {"headline", headline},
{"body", body}, {"score", A{J(t.score[0]), J(t.score[1])}}, {"side", side ? "away" : "home"},
{"player", almanac_person(s, e.player)}, {"other", almanac_person(s, e.other)}});
}
if (!mo.event && mo.phase) {
// the whistle: kickoff, half time and the end of each ticker match, with the score then
const std::string phase = mo.phase;
const char* kind = phase == "kickoff" ? "kickoff" : phase == "interval" ? "interval"
: phase == "fulltime" || phase == "shootout_end" ? "fulltime" : nullptr;
for (size_t k = 0; kind && k < human.size(); ++k) {
const AlmanacSeason& s = *human[k].season;
const AlmanacMatch& m = s.matches[human[k].index];
const Tally& t = tally[k];
const std::string mid = match_id(s, human[k].index);
const std::string score = std::to_string(t.score[0]) + ":" + std::to_string(t.score[1]);
const std::string headline = phase == "kickoff" ? "Anpfiff" : phase == "interval" ? "Halbzeit" : "Abpfiff";
const std::string body = phase == "kickoff" ? s.clubs[m.home].name + " gegen " + s.clubs[m.away].name + ": Der Ball rollt."
: phase == "interval" ? "Zur Pause steht es " + score + "."
: phase == "shootout_end" ? "Das Elfmeterschießen ist entschieden."
: mo.minute > 90 ? "Endstand nach Verlängerung: " + score + "." : "Endstand: " + score + ".";
events.push_back(O{{"id", mid + ":event:" + std::to_string(events.size())}, {"sequence", int64_t(frames.size())},
{"match_id", mid}, {"minute", mo.minute}, {"kind", kind}, {"headline", headline}, {"body", body},
{"score", A{J(t.score[0]), J(t.score[1])}}, {"side", "home"}, {"player", nullptr}, {"other", nullptr}});
}
}
A scores;
for (size_t k = 0; k < human.size(); ++k) {
const Tally& t = tally[k];
scores.push_back(O{{"match_id", match_id(*human[k].season, human[k].index)},
{"score", A{J(t.score[0]), J(t.score[1])}}, {"chances", A{J(t.chances[0]), J(t.chances[1])}},
{"yellow", A{J(t.yellow[0]), J(t.yellow[1])}}, {"red", A{J(t.red[0]), J(t.red[1])}},
{"shootout", A{J(t.shootout[0]), J(t.shootout[1])}},
{"players", A{J(11 - t.red[0]), J(11 - t.red[1])}}});
}
const char* phase = mo.phase ? mo.phase : mo.minute <= 45 ? "first_half" : mo.minute <= 90 ? "second_half"
: mo.minute <= 120 ? "extra_time" : "shootout";
A standings;
const bool final_whistle = mo.phase && (std::string(mo.phase) == "fulltime" || std::string(mo.phase) == "shootout_end");
for (LiveLeague& l : live_leagues)
if (J table = live_table(l, mo.minute, final_whistle); !std::holds_alternative<std::nullptr_t>(table.value))
standings.push_back(std::move(table));
frames.push_back(O{{"sequence", int64_t(frames.size())}, {"minute", mo.minute}, {"phase", phase},
{"matches", std::move(scores)}, {"events", events}, {"standings", std::move(standings)}});
}
const AlmanacSeason& first = *human.front().season;
return O{{"ok", true}, {"schema", "openbmh-live-fixture@1"}, {"source", "engine-recording"},
{"fixture_id", "live:" + std::to_string(first.start_year) + "-" + std::to_string(human.front().index)},
{"source_revision", int64_t(revision)}, {"date", iso_date(first.matches[human.front().index].date, first.display_start_year)},
{"role", owners.empty() ? "club" : std::get<O>(std::get<O>(owners.front().value).at("team").value).at("role")},
{"surface", "outdoor"}, {"duration", extra ? 120 : 90}, {"field_count", 11}, {"owners", std::move(owners)},
{"matches", std::move(matches)}, {"frames", std::move(frames)}, {"conference", std::move(conference)},
{"notice", "Aufzeichnung der Engine: die Spiele des letzten Anstoßes"}};
}
// Modern's eleven of the day: for every league with a match of a human manager in the kickoff,
// the best starters of that league's matches by what the almanac recorded (goals, assists,
// cards, the result, clean sheets), one goalkeeper, three defenders, four midfielders and
// three forwards. Nothing is drawn at random and no rating of the original is used; the
// current strength of a player only breaks ties.
cli::Json recent_results(const ModernState& g, const std::string& club_id, size_t count) {
A rows;
for (const auto& s : seasons_of(g))
for (const auto& m : s.matches) {
if (m.home >= s.clubs.size() || m.away >= s.clubs.size()) continue;
const bool home = s.clubs[m.home].id == club_id;
if (!home && s.clubs[m.away].id != club_id) continue;
const int own = home ? m.home_goals : m.away_goals, other = home ? m.away_goals : m.home_goals;
int balance = own - other;
if (!balance && m.decided == 2)
balance = home ? int(m.home_shootout) - int(m.away_shootout) : int(m.away_shootout) - int(m.home_shootout);
rows.push_back(O{{"form", balance > 0 ? "S" : balance < 0 ? "N" : "U"},
{"score", std::to_string(own) + ":" + std::to_string(other)},
{"opponent", s.clubs[home ? m.away : m.home].name}, {"home", home}});
}
if (rows.size() > count) rows.erase(rows.begin(), rows.end() - std::ptrdiff_t(count));
return rows;
}
cli::Json club_analysis(const ModernState& g, const std::string& club_id) {
const auto seasons = seasons_of(g);
A history;
for (const auto& s : seasons)
for (const auto& table : s.tables)
for (const auto& row : table.rows)
if (row.club < s.clubs.size() && s.clubs[row.club].id == club_id) {
std::string league = "Liga";
for (const auto& l : s.leagues) if (l.index == int(table.league)) league = l.name;
history.push_back(O{{"year", s.start_year}, {"rank", int(row.rank)}, {"points", int(row.points)},
{"goalsFor", int(row.goals_for)}, {"goalsAgainst", int(row.goals_against)}, {"league", league}});
}
if (seasons.empty() || seasons.back().season != g.almanac.current.season || g.almanac.current.season < 0)
return O{{"available", false}, {"history", std::move(history)}};
const auto& s = seasons.back();
struct Record { int played = 0, won = 0, drawn = 0, lost = 0, goals_for = 0, goals_against = 0; };
const auto record = [](const Record& r) {
return O{{"played", r.played}, {"won", r.won}, {"drawn", r.drawn}, {"lost", r.lost}, {"goalsFor", r.goals_for},
{"goalsAgainst", r.goals_against}, {"points", r.won * 3 + r.drawn}};
};
Record home_record, away_record, first_for, first_against;
int buckets[6][2] = {}, kinds[4][2] = {}, chances[2] = {}, goals[2] = {}, yellow[2] = {}, red[2] = {}, league = -1;
std::map<uint16_t, std::pair<int, int>> scorers; // goals, assists
A matches, points;
int total = 0;
for (const auto& m : s.matches) {
if (m.home >= s.clubs.size() || m.away >= s.clubs.size()) continue;
const bool home = s.clubs[m.home].id == club_id;
if (!home && s.clubs[m.away].id != club_id) continue;
const int own_side = home ? 0 : 1;
const int own = home ? m.home_goals : m.away_goals, other = home ? m.away_goals : m.home_goals;
auto& side_record = home ? home_record : away_record;
++side_record.played; side_record.goals_for += own; side_record.goals_against += other;
(own > other ? side_record.won : own < other ? side_record.lost : side_record.drawn)++;
int first = -1; // who scored the first goal: 0 own, 1 opponent
for (const auto& e : m.events) {
const int mine = e.side == own_side ? 0 : 1;
if (e.kind == AlmanacEventKind::Goal || e.kind == AlmanacEventKind::Miss) ++chances[mine];
if (e.kind == AlmanacEventKind::Goal) {
++goals[mine];
++buckets[std::clamp((int(e.minute) - 1) / 15, 0, 5)][mine];
++kinds[std::min<int>(e.detail, 3)][mine];
if (first < 0) first = mine;
if (!mine) {
if (e.player != kAlmanacNone) ++scorers[e.player].first;
if (e.other != kAlmanacNone) ++scorers[e.other].second;
}
} else if (e.kind == AlmanacEventKind::YellowCard) ++yellow[mine];
else if (e.kind == AlmanacEventKind::RedCard || e.kind == AlmanacEventKind::SecondYellow) ++red[mine];
}
if (first >= 0) {
auto& r = first ? first_against : first_for;
++r.played; (own > other ? r.won : own < other ? r.lost : r.drawn)++;
}
if (m.type == 0) {
league = m.league;
total += own > other ? 3 : own == other ? 1 : 0;
points.push_back(total);
}
matches.push_back(O{{"opponent", s.clubs[home ? m.away : m.home].name}, {"home", home}, {"league", m.type == 0},
{"round", int(m.round)}, {"goalsFor", own}, {"goalsAgainst", other}, {"attendance", int64_t(m.attendance)}});
}
// the league beside it: goals and chances per team and match, points per team and match
int64_t league_matches = 0, league_goals = 0, league_chances = 0, league_points = 0;
if (league >= 0)
for (const auto& m : s.matches) {
if (m.type != 0 || m.league != league) continue;
++league_matches;
league_points += m.home_goals == m.away_goals ? 2 : 3;
for (const auto& e : m.events) {
if (e.kind == AlmanacEventKind::Goal || e.kind == AlmanacEventKind::Miss) ++league_chances;
if (e.kind == AlmanacEventKind::Goal) ++league_goals;
}
}
std::vector<std::pair<uint16_t, std::pair<int, int>>> ranked(scorers.begin(), scorers.end());
std::stable_sort(ranked.begin(), ranked.end(), [](const auto& a, const auto& b) {
return a.second.first * 2 + a.second.second > b.second.first * 2 + b.second.second;
});
A scorer_rows;
for (size_t i = 0; i < ranked.size() && i < 8; ++i) {
const uint16_t p = ranked[i].first;
if (p >= s.players.size()) continue;
const auto& player = s.players[p];
scorer_rows.push_back(O{{"id", player.id}, {"name", player.first.empty() ? player.last : player.first + " " + player.last},
{"goals", ranked[i].second.first}, {"assists", ranked[i].second.second}});
}
A bucket_rows, kind_rows;
for (int b = 0; b < 6; ++b) bucket_rows.push_back(O{{"from", b * 15 + 1}, {"for", buckets[b][0]}, {"against", buckets[b][1]}});
for (int k = 0; k < 4; ++k) kind_rows.push_back(O{{"kind", k}, {"for", kinds[k][0]}, {"against", kinds[k][1]}});
std::string league_name;
for (const auto& l : s.leagues) if (l.index == league) league_name = l.name;
return O{{"available", home_record.played + away_record.played > 0}, {"year", s.start_year}, {"leagueName", league_name},
{"matches", std::move(matches)}, {"points", std::move(points)}, {"buckets", std::move(bucket_rows)},
{"kinds", std::move(kind_rows)}, {"home", record(home_record)}, {"away", record(away_record)},
{"firstFor", record(first_for)}, {"firstAgainst", record(first_against)},
{"chances", O{{"for", chances[0]}, {"against", chances[1]}}}, {"goals", O{{"for", goals[0]}, {"against", goals[1]}}},
{"cards", O{{"yellow", yellow[0]}, {"red", red[0]}, {"yellowAgainst", yellow[1]}, {"redAgainst", red[1]}}},
{"league", O{{"matches", league_matches}, {"goals", league_goals}, {"chances", league_chances}, {"points", league_points}}},
{"scorers", std::move(scorer_rows)}, {"history", std::move(history)}};
}
cli::Json team_of_the_day(const ModernState& g, uint32_t from_date, uint32_t until_date) {
std::map<std::string, int> runtime; // world player id -> runtime index
for (size_t p = 0; p < g.world_player_id.size(); ++p)
if (!g.world_player_id[p].empty()) runtime[g.world_player_id[p]] = int(p);
A out;
const auto seasons = seasons_of(g);
for (const auto& s : seasons) {
std::set<int> leagues;
for (const auto& m : s.matches)
if (m.date >= from_date && m.date <= until_date && m.type == 0 && m.league < kLeagueCount &&
(m.home_manager >= 0 || m.away_manager >= 0)) leagues.insert(m.league);
for (const int league : leagues) {
struct Candidate { int score = 0, strength = 0, position = 0; uint16_t player = 0, club = 0; };
std::vector<Candidate> candidates;
for (const auto& m : s.matches) {
if (m.date < from_date || m.date > until_date || m.type != 0 || m.league != league) continue;
for (int side = 0; side < 2; ++side) {
const int scored = side ? m.away_goals : m.home_goals, conceded = side ? m.home_goals : m.away_goals;
const auto& lineup = m.lineup[size_t(side)];
for (size_t i = 0; i < lineup.size() && i < 11; ++i) {
const uint16_t player = lineup[i];
if (player == kAlmanacNone || player >= s.players.size()) continue;
const auto at = runtime.find(s.players[player].id);
if (at == runtime.end() || size_t(at->second) >= g.players.size()) continue;
const Player& now = g.players[size_t(at->second)];
Candidate c;
c.player = player, c.club = side ? m.away : m.home;
c.position = std::clamp(int(now.position()), 0, 3), c.strength = int(now.strength());
c.score = 10 + (scored > conceded ? 4 : scored == conceded ? 1 : 0);
if (conceded == 0) c.score += c.position == 0 ? 8 : c.position == 1 ? 5 : 0;
if (c.position == 0) c.score -= 2 * conceded;
for (const auto& e : m.events) {
if (e.kind == AlmanacEventKind::Goal && e.side == side && e.player == player) c.score += 12;
if (e.kind == AlmanacEventKind::Goal && e.side == side && e.other == player) c.score += 6;
if (e.kind == AlmanacEventKind::YellowCard && e.side == side && e.player == player) c.score -= 4;
if ((e.kind == AlmanacEventKind::RedCard || e.kind == AlmanacEventKind::SecondYellow) && e.side == side &&
e.player == player) c.score -= 12;
}
candidates.push_back(c);
}
}
}
std::stable_sort(candidates.begin(), candidates.end(), [&](const Candidate& a, const Candidate& b) {
if (a.score != b.score) return a.score > b.score;
if (a.strength != b.strength) return a.strength > b.strength;
return s.players[a.player].id < s.players[b.player].id;
});
static constexpr int kWanted[4] = {1, 3, 4, 3};
static constexpr const char* kPositions[4] = {"gk", "def", "mid", "fwd"};
A players;
bool complete = true;
for (int position = 0; position < 4; ++position) {
int taken = 0;
for (const Candidate& c : candidates) {
if (c.position != position || taken == kWanted[position]) continue;
++taken;
players.push_back(O{{"playerId", s.players[c.player].id}, {"name", player_name(s.players[c.player])},
{"teamId", s.clubs[c.club].id}, {"club", s.clubs[c.club].name},
{"position", kPositions[position]}, {"score", c.score}});
}
complete = complete && taken == kWanted[position];
}
if (!complete) continue;
const Competition c = league_competition(s, league);
out.push_back(O{{"competitionId", c.id}, {"competition", c.name}, {"formation", "3-4-3"}, {"players", std::move(players)}});
}
}
return out;
}
cli::Json almanac_matches_between(const ModernState& g, uint32_t from_date, uint32_t until_date) {
A out;
for (const auto& s : seasons_of(g))
for (size_t i = 0; i < s.matches.size(); ++i)
if (s.matches[i].date >= from_date && s.matches[i].date <= until_date) out.push_back(almanac_match(g, s, i));
return out;
}
cli::Json query_news(const ModernState& g, const std::string& team, const std::string& from, const std::string& until) {
A events;
const auto entity = [](const AlmanacClub& c) {
return J(O{{"id", c.id}, {"name", c.name}, {"kind", c.id.starts_with("nt:") ? "national" : "club"}});
};
const auto competition = [](const AlmanacSeason& s, const Competition& c, const AlmanacMatch* m) {
const std::string kind = c.type == "league" ? "league" : m && m->type - 1 == 10 ? "friendly" : "cup";
return J(O{{"id", c.id}, {"name", c.name}, {"kind", kind}, {"season", season_label(s.start_year)}});
};
const auto add = [&](const std::string& type, const std::string& key, const std::string& date, const J& scope, O data) {
if (date < from || date > until) return;
events.push_back(O{{"id", "press-event:" + type + ":" + key + ":" + team}, {"type", type}, {"date", date},
{"scope", scope}, {"data", std::move(data)}, {"variant", nullptr}});
};
for (const AlmanacSeason& s : seasons_of(g)) {
int own_club = -1;
for (size_t c = 0; c < s.clubs.size(); ++c)
if (s.clubs[c].id == team) own_club = int(c);
if (own_club < 0) continue;
const J me = entity(s.clubs[size_t(own_club)]);
const J scope = O{{"kind", std::get<O>(me.value).at("kind")}, {"id", team}, {"name", s.clubs[size_t(own_club)].name}};
// the runs over the competitive matches: wins, unbeaten, winless, losses
int wins = 0, unbeaten = 0, winless = 0, losses = 0;
for (size_t i = 0; i < s.matches.size(); ++i) {
const AlmanacMatch& m = s.matches[i];
const int side = m.home == own_club ? 0 : m.away == own_club ? 1 : -1;
if (side < 0) continue;
const AlmanacClub& other = s.clubs[side ? m.home : m.away];
const std::string id = match_id(s, i), date = iso_date(m.date, s.display_start_year);
const Competition c = competition_of(g, s, m);
const int own = side ? m.away_goals : m.home_goals, opp = side ? m.home_goals : m.away_goals;
// trailing at some point, and the minute of the deciding goal (the goal that put the
// winner one ahead of the loser's final total; none for a draw)
bool trailed = false;
int score[2] = {0, 0}, decisive = -1;
for (const auto& e : m.events) {
if (e.kind != AlmanacEventKind::Goal) continue;
const int k = e.side == side ? 0 : 1;
++score[k];
if (score[0] < score[1]) trailed = true;
if (own > opp && k == 0 && score[0] == opp + 1) decisive = e.minute;
if (opp > own && k == 1 && score[1] == own + 1) decisive = e.minute;
}
const bool shootout_won = side ? m.away_shootout > m.home_shootout : m.home_shootout > m.away_shootout;
O data{{"team", me}, {"opponent", entity(other)}, {"competition", competition(s, c, &m)}, {"matchId", id},
{"score", O{{"for", own}, {"against", opp}}}, {"venue", side ? "away" : "home"}, {"trailed", trailed},
{"minute", decisive >= 0 ? J(decisive) : J(nullptr)}, {"outcome", own > opp ? "win" : own < opp ? "loss" : "draw"}};
const bool friendly = m.type != 0 && m.type - 1 == 10, cup = m.type != 0 && !friendly;
bool final_match = false;
for (const AlmanacWinner& w : s.winners)
if (cup && w.type == m.type && w.detail == 0 && w.date == m.date && w.runner_up != 0xffff &&
((w.winner == m.home && w.runner_up == m.away) || (w.winner == m.away && w.runner_up == m.home)))
final_match = true;
if (cup) {
data["round"] = int(m.round);
if (m.decided == 2) {
O pens = data;
pens["shootout"] = O{{"for", int(side ? m.away_shootout : m.home_shootout)},
{"against", int(side ? m.home_shootout : m.away_shootout)}};
pens["outcome"] = shootout_won ? "win" : "loss";
add("cup.penalties", id, date, scope, std::move(pens));
} else if (m.decided == 1) {
add("cup.extra_time", id, date, scope, data);
}
add(final_match ? "cup.final_result" : "cup.round_result", id, date, scope, std::move(data));
} else {
add("match.result", id, date, scope, std::move(data));
}
// the team's players: sent off, injured
for (size_t k = 0; k < m.events.size(); ++k) {
const AlmanacEvent& e = m.events[k];
if (e.side != side) continue;
const std::string key = id + "-" + std::to_string(k);
if (e.kind == AlmanacEventKind::RedCard || e.kind == AlmanacEventKind::SecondYellow)
add("player.sent_off", key, date, scope, O{{"player", almanac_person(s, e.player)}, {"team", me}, {"minute", int(e.minute)}});
if (e.kind == AlmanacEventKind::Injury)
add("player.injury", key, date, scope, O{{"player", almanac_person(s, e.player)}, {"team", me}, {"minute", int(e.minute)}});
}
if (friendly) continue; // friendlies do not count for the runs
const bool won = own > opp || (m.decided == 2 && shootout_won);
const bool lost = own < opp || (m.decided == 2 && !shootout_won);
wins = won ? wins + 1 : 0, losses = lost ? losses + 1 : 0;
unbeaten = lost ? 0 : unbeaten + 1, winless = won ? 0 : winless + 1;
const auto run = [&](const char* type, int count, std::initializer_list<int> marks) {
for (int mark : marks)
if (count == mark) add(type, id, date, scope, O{{"team", me}, {"matches", count}});
};
run("run.wins", wins, {3, 5, 8, 10, 15});
run("run.unbeaten", unbeaten, {5, 10, 15, 20, 30});
run("run.winless", winless, {5, 8, 10, 15});
run("run.losses", losses, {3, 5, 8, 10});
}
// the season's end: league position and champion (dated on the league's last match day), titles
for (const AlmanacTable& t : s.tables)
for (const AlmanacStanding& r : t.rows) {
if (r.club != own_club) continue;
const Competition c = league_competition(s, t.league);
uint32_t last = 0;
for (const auto& m : s.matches)
if (m.type == 0 && m.league == t.league) last = std::max(last, m.date);
const std::string date = iso_date(last, s.display_start_year), key = season_label(s.start_year) + "-" + c.id;
O data{{"team", me}, {"competition", competition(s, c, nullptr)}, {"season", season_label(s.start_year)},
{"position", int(r.rank)}, {"points", int(r.points)}};
add("league.position", key, date, scope, data);
if (r.rank == 1) add("league.champion", key, date, scope, std::move(data));
}
for (const AlmanacWinner& w : s.winners) {
if (w.type == 0 || w.winner != own_club) continue;
const Competition c = competition_of(g, s, w);
add(w.detail == 1 ? "indoor.won" : "cup.won", season_label(s.start_year) + "-" + c.id, iso_date(w.date, s.display_start_year),
scope, O{{"team", me}, {"competition", competition(s, c, nullptr)}, {"season", season_label(s.start_year)}});
}
}
std::stable_sort(events.begin(), events.end(), [](const J& a, const J& b) {
return *std::get<O>(a.value).at("date").string() < *std::get<O>(b.value).at("date").string();
});
return O{{"ok", true}, {"events", std::move(events)}};
}
} // namespace bmh::modern
namespace bmh::modern {
cli::Json manager_employments(const ModernState& g, int manager, const std::string& manager_id) {
// the teams a human manager led, from the recorded matches: a new employment begins when
// the team of his matches changes (a club and the national team run side by side)
struct Stint { std::string team, name, kind; uint32_t from = 0, until = 0; int display_year = 0; };
std::vector<Stint> stints;
for (const AlmanacSeason& s : seasons_of(g))
for (const AlmanacMatch& m : s.matches)
for (int side = 0; side < 2; ++side) {
const int8_t mi = side ? m.away_manager : m.home_manager;
if (mi < 0 || size_t(mi) >= s.managers.size() || s.managers[size_t(mi)].index != manager) continue;
const AlmanacClub& c = s.clubs[side ? m.away : m.home];
// national: a world's nt: id, or without a world a runtime number from no_team() on
bool national = c.id.starts_with("nt:");
if (c.id.starts_with("team:")) try { national = std::stoi(c.id.substr(5)) >= no_team(); } catch (const std::exception&) {}
const std::string kind = national ? "national" : "club";
// the same team: by its world id, without a world by its name (runtime numbers change)
const auto same = [&](const Stint& st) { return c.id.starts_with("team:") ? st.name == c.name : st.team == c.id; };
Stint* open = nullptr;
for (auto it = stints.rbegin(); it != stints.rend() && !open; ++it)
if (it->kind == kind) open = &*it;
if (open && same(*open)) { open->until = m.date, open->team = c.id; continue; } // the id as last seen
stints.push_back({c.id, c.name, kind, m.date, m.date, s.display_start_year});
}
// the last stint of each kind runs until the career's end (resigned, or the set duration
// ran out); an earlier one ended with its last match (the reason is not recorded: null)
const bool ended = !g.career_end_reason.empty();
const char* end_reason = g.career_end_reason == "last_human_resigned" ? "resigned" : "career_end";
const std::string end_date = ended ? iso_date(g.career_end_date, g.display_start_year) : std::string{};
A out;
for (size_t i = 0; i < stints.size(); ++i) {
const Stint& st = stints[i];
bool current = true; // the last stint of its kind
for (size_t k = i + 1; k < stints.size(); ++k) current &= stints[k].kind != st.kind;
out.push_back(O{{"id", "employment:" + manager_id.substr(manager_id.find(':') + 1) + "-" + std::to_string(i + 1)},
{"managerId", manager_id}, {"teamId", st.team},
{"role", st.kind == "national" ? "national_coach" : "club_manager"},
{"from", iso_date(st.from, st.display_year)},
{"until", current ? (ended ? J(end_date) : J(nullptr)) : J(iso_date(st.until, st.display_year))},
{"endReason", current && ended ? J(end_reason) : J(nullptr)}});
}
return out;
}
} // namespace bmh::modern