import type { Metadata } from 'next';
import { notFound } from 'next/navigation';

import { getCreationList } from '@/services/creations';
import {
  branchDisplayName,
  getCreatorStatistics,
  getOverviewStatistics,
  getProgramStatistics,
  getVideoStatistics,
} from '@/services/statistics';

import { reportApiError } from '@/utils/apiError';
import { metaAttributes110 } from '@/utils/filterUtils';
import { getLocalizedAlternates } from '@/utils/seo';

import StoryPage from './StoryPage';
import classmates from './_data/classmates.json';
import mentors from './_data/mentors.json';
import snapshot from './_data/snapshot.json';
import titleMotifs from './_data/title-motifs.json';
import { stateAwardStatistics } from './awards';
import { CreatorTotalProvider, type Picture } from './story';
import {
  DATABASE_KEYS,
  MENTOR_KEYS,
  OVERVIEW_KEYS,
  SIZE_KEYS,
  SNAPSHOT_KEYS,
  type TitleMotif,
} from './types';

// Retry partial outages within five minutes; successful API data keeps its cache.
export const revalidate = 300;

// Indexed like the rest of the site (robots come from the layout). Hungarian only: the story and
// its data are not translated, so there is no English alternate.
export const metadata: Metadata = {
  title: 'Felfedezés',
  description:
    'Mikor és hol készültek az alkotások, kik alkották őket, és milyen utat jártak be? Fedezze fel az A–Z OPUS-ban szereplő kortárs magyar művészeket a számok tükrében!',
  alternates: getLocalizedAlternates('hu', '/felfedezes', ['hu']),
};

const pick = <T, K extends keyof T>(source: T, keys: readonly K[]) =>
  Object.fromEntries(keys.map((key) => [key, source[key]])) as Pick<T, K>;

// The story shows eight pairs at a time: a part of the list is enough for its redraws, and the
// whole list stays out of the browser. A new draw comes with each rendering of the page.
const CLASSMATE_POOL = 40;
const drawClassmates = () =>
  classmates.pairs
    .map((pair) => ({ pair, order: Math.random() }))
    .sort((a, b) => a.order - b.order)
    .slice(0, CLASSMATE_POOL)
    .map(({ pair }) => pair);

// A day's random featured pictures per branch (the fetch cache holds them); the browser shows three.
const BRANCH_PICTURES = 12;
async function getBranchPictures() {
  // Keyed by the branch names of the statistics, which the story matches them by.
  const byBranch: Record<string, Picture[]> = {};
  // One after the other: the API's database pool is small, and this runs only on revalidation.
  for (const branch of metaAttributes110) {
    try {
      const creations = await getCreationList({
        contentType: [branch.culturalEntityTypeId],
        imageNeeded: true,
        featuredContent: true,
        random: true,
        maxResults: BRANCH_PICTURES,
      });
      byBranch[branchDisplayName(branch.name)] = creations.flatMap((creation) =>
        creation.fokep?.id && creation.nev
          ? [
              {
                id: creation.alkotasAzonosito,
                title: creation.nev,
                year: creation.labelYear,
                image: creation.fokep.id,
                creator:
                  creation.alkoto.map((person) => person.megjelenitendoNev).join(', ') || null,
              },
            ]
          : []
      );
    } catch (error) {
      reportApiError(error, `Branch pictures unavailable (${branch.name}):`);
      // Optional pictures must not hide the other branches or statistics.
      byBranch[branchDisplayName(branch.name)] = [];
    }
  }
  return byBranch;
}

const motif = ({ matched, ranking }: TitleMotif): TitleMotif => ({
  matched,
  ranking: ranking.map(({ label, value }) => ({ label, value })),
});

async function optionalStatistics<T>(request: Promise<T>, context: string): Promise<T | null> {
  try {
    return await request;
  } catch (error) {
    reportApiError(error, context);
    return null;
  }
}

export default async function NumbersPage({ params }: { params: Promise<{ locale: string }> }) {
  const { locale } = await params;
  if (locale !== 'hu') notFound();

  // Isolate backend failures while preserving Next.js rendering/navigation signals.
  const [overview, creators, programs, videos] = await Promise.all([
    optionalStatistics(getOverviewStatistics(), 'Overview statistics unavailable:'),
    optionalStatistics(getCreatorStatistics(), 'Creator statistics unavailable:'),
    optionalStatistics(getProgramStatistics(), 'Program statistics unavailable:'),
    optionalStatistics(getVideoStatistics(), 'Video statistics unavailable:'),
  ]);
  const data = overview ? pick(overview, OVERVIEW_KEYS) : null;
  return (
    <CreatorTotalProvider value={data?.totals.creators ?? null}>
      <StoryPage
        data={data}
        creatorsAvailable={creators !== null}
        generatedAt={{
          overview: overview?.generatedAt ?? null,
          creators: creators?.generatedAt ?? null,
          programs: programs?.generatedAt ?? null,
        }}
        snapshot={{
          ...pick(snapshot, SNAPSHOT_KEYS),
          birthDecades: creators?.birthDecades ?? [],
          bornAbroadShare: creators?.bornAbroadShare ?? 0,
          countries: creators?.countries ?? [],
          ageBins: creators?.ageBins ?? [],
          ageAtCreation: creators?.ageAtCreation ?? [],
          oldCreationShare: creators?.oldCreationShare ?? 0,
          oldestWorkers: creators?.oldestWorkers ?? [],
          ...stateAwardStatistics(creators?.ageAtAward ?? []),
          database: {
            ...pick(snapshot.database, DATABASE_KEYS),
            sizes: pick(snapshot.database.sizes, SIZE_KEYS),
          },
        }}
        birthPlaces={creators?.birthPlaces ?? []}
        programs={programs}
        videoStatistics={videos}
        classmatePairs={drawClassmates()}
        mentors={pick(mentors, MENTOR_KEYS)}
        motifs={{
          total: titleMotifs.total,
          seasons: motif(titleMotifs.seasons),
          animals: motif(titleMotifs.animals),
        }}
        branchPictures={await getBranchPictures()}
      />
    </CreatorTotalProvider>
  );
}
