import type { AwardAges } from '@/services/statistics';

/*
 * The state awards the story counts, by their id in the API, from the 33-award list
 * (MMA_tagok_altal_kapott_allami_kozep_dijak.xlsx). The grades of the Munka Érdemrend are left
 * out: they are one award in the database. A group of more than one id counts as one award (the
 * renamed variants of one title, for example); its label is the name shown on the page.
 */
export const STATE_AWARD_GROUPS: { ids: number[]; label?: string }[] = [
  { ids: [11] }, // Apáczai Csere János-díj
  { ids: [18] }, // Balázs Béla-díj
  { ids: [19] }, // Balogh Rudolf-díj
  { ids: [20] }, // Bánffy Miklós-díj
  { ids: [35] }, // Erkel Ferenc-díj
  { ids: [38] }, // Ferenczy Noémi-díj
  { ids: [40] }, // Forster Gyula-díj
  { ids: [45] }, // Harangozó Gyula-díj
  { ids: [54] }, // Jászai Mari-díj
  { ids: [56] }, // József Attila-díj
  { ids: [59] }, // Kiváló Munkáért
  { ids: [63] }, // Kós Károly-díj
  { ids: [81] }, // Liszt Ferenc-díj
  // The renamed variants of a title as one award, linked in the database as predecessor and
  // successor: Magyar Népköztársaság / Magyar Köztársaság / Magyarország.
  { ids: [103, 92, 108], label: 'Érdemes Művész' },
  { ids: [104, 93, 109], label: 'Kiváló Művész' },
  { ids: [88, 107], label: 'Babérkoszorú díj' },
  { ids: [112] }, // Martin György-díj
  { ids: [116] }, // Mőcsényi Mihály-díj
  { ids: [119] }, // Munkácsy Mihály-díj
  { ids: [127] }, // Németh Lajos-díj
  { ids: [128] }, // Nemzet Művésze
  { ids: [131] }, // Népművészet Ifjú Mestere
  { ids: [132] }, // Népművészet Mestere
  { ids: [147] }, // Szabolcsi Bence-díj
  { ids: [155] }, // Táncsics Mihály-díj
  { ids: [160] }, // Ybl Miklós-díj
];

const KOSSUTH_PRIZE_ID = 65;
// An award shows its ages only with this many laureates of known age.
const MIN_LAUREATES = 9;
const LADDER_STEPS = 12;

const median = (values: number[]) => {
  const sorted = [...values].sort((a, b) => a - b);
  const middle = Math.floor(sorted.length / 2);
  return sorted.length % 2 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2;
};

/** Each creator's age at the first receipt among the given awards. */
function firstAges(rows: AwardAges[], ids: number[]) {
  const ages = new Map<string, number>();
  for (const row of rows) {
    if (!ids.includes(row.awardId)) continue;
    for (const { id, age } of row.ages) ages.set(id, Math.min(ages.get(id) ?? Infinity, age));
  }
  return ages;
}

/**
 * The award figures of the story from the API's ages: every receipt comes with the creator, and
 * only each creator's first receipt counts. Nominations are not in the data.
 */
export function stateAwardStatistics(rows: AwardAges[]) {
  const groups = STATE_AWARD_GROUPS.map(({ ids, label }) => ({
    ids,
    label: label ?? rows.find((row) => row.awardId === ids[0])?.award ?? '',
    ages: firstAges(rows, ids),
  })).filter((group) => group.label && group.ages.size);

  // Age at the first receipt, per award.
  const ageAtAward = groups
    .map(({ label, ages }) => {
      const known = [...ages.values()].filter((age) => age > 10 && age < 105).sort((a, b) => a - b);
      return { award: label, ages: known, median: known.length ? median(known) : null };
    })
    .filter((item) => item.ages.length >= MIN_LAUREATES)
    .sort((a, b) => b.ages.length - a.ages.length || a.award.localeCompare(b.award, 'hu'));

  // The road to the Kossuth Prize: the awards its laureates got before it, and how many years earlier.
  const kossuth = firstAges(rows, [KOSSUTH_PRIZE_ID]);
  const yearsBefore = (ages: Map<string, number>) =>
    [...ages]
      .filter(([id, age]) => kossuth.has(id) && age < kossuth.get(id)!)
      .map(([id, age]) => kossuth.get(id)! - age);
  // The steps are the twelve awards most often before it, each award counted on its own; a group
  // among them is one step with its awards' figures together, so there may be fewer steps.
  const stepIds = groups
    .flatMap((group) => group.ids)
    .map((id) => ({
      id,
      award: rows.find((row) => row.awardId === id)?.award ?? '',
      count: yearsBefore(firstAges(rows, [id])).length,
    }))
    .filter((item) => item.count)
    .sort((a, b) => b.count - a.count || a.award.localeCompare(b.award, 'hu'))
    .slice(0, LADDER_STEPS)
    .map((item) => item.id);
  const kossuthLadder = groups
    .filter((group) => group.ids.some((id) => stepIds.includes(id)))
    .map(({ label, ages }) => {
      const gaps = yearsBefore(ages);
      return { label, value: gaps.length, years: gaps.length ? median(gaps) : null };
    })
    .sort((a, b) => b.value - a.value || a.label.localeCompare(b.label, 'hu'));

  // The first of any of these awards.
  const first = new Map<string, number>();
  for (const { ages } of groups) {
    for (const [id, age] of ages) first.set(id, Math.min(first.get(id) ?? Infinity, age));
  }
  const firstAwardAges = [...first.values()].filter((age) => age > 3 && age < 100);
  const careerMilestones = [
    {
      label: 'Első díj',
      median: firstAwardAges.length ? median(firstAwardAges) : null,
      count: firstAwardAges.length,
    },
  ];

  return { ageAtAward, kossuthLadder, careerMilestones };
}
