import {
  statisticsGetCreators,
  statisticsGetOverview,
  statisticsGetPrograms,
  statisticsGetVideo,
} from '@/generated/azopus-api';
import type { CreatorCount } from '@/generated/models';

type Ranked = { label: string; value: number };

export type OverviewStatistics = {
  generatedAt: string | null;
  totals: {
    creations: number;
    creators: number;
    branches: number;
    places: number;
    lifeEvents: number;
    institutions: number;
    programs: number;
  };
  creationsByBranch: Ranked[];
  creatorsByBranch: Ranked[];
  workBuckets: Ranked[];
  decades: number[];
  decadeMatrix: { branch: string; counts: number[] }[];
  budapestShare: number;
  /** [longitude, latitude] */
  points: [number, number][];
};

const capitalize = (text: string) => text.charAt(0).toUpperCase() + text.slice(1);

// The story's names for the branches where the database's name is too long for the charts.
const BRANCH_DISPLAY_NAMES: Record<string, string> = {
  'iparművészet és tervezőművészet': 'Ipar- és tervezőművészet',
};

/** A branch as the /felfedezes page names it: capitalised, and shortened where it has to be. */
export const branchDisplayName = (name: string) =>
  BRANCH_DISPLAY_NAMES[name.trim().toLowerCase()] ?? capitalize(name);

const toRanked = (
  rows: { label?: string; value?: number }[] = [],
  label = (text: string) => text
) => rows.map((row) => ({ label: label(row.label ?? ''), value: row.value ?? 0 }));

/**
 * The database overview of the /felfedezes page. The API sends the branch names in lower case and
 * also a branch without any creation; the story expects display names and the 10 real branches.
 */
export async function getOverviewStatistics(options?: RequestInit): Promise<OverviewStatistics> {
  const { data } = await statisticsGetOverview(options);
  const { totals, decades, decadeMatrix, budapestShare, points } = data;
  if (!totals || !decades?.length || !decadeMatrix?.length || !points) {
    throw new Error('Invalid API response: incomplete overview statistics');
  }
  const creationsByBranch = toRanked(data.creationsByBranch, branchDisplayName);
  const empty = new Set(creationsByBranch.filter((row) => !row.value).map((row) => row.label));

  return {
    generatedAt: data.generatedAt ?? null,
    totals: {
      creations: totals.creations ?? 0,
      creators: totals.creators ?? 0,
      branches: totals.branches ?? 0,
      places: totals.places ?? 0,
      lifeEvents: totals.lifeEvents ?? 0,
      institutions: totals.institutions ?? 0,
      programs: totals.programs ?? 0,
    },
    creationsByBranch: creationsByBranch.filter((row) => !empty.has(row.label)),
    creatorsByBranch: toRanked(data.creatorsByBranch, branchDisplayName),
    // The editors' wording for the top bucket: "100+" rather than the API's "> 100".
    workBuckets: toRanked(data.workBuckets, (label) => label.replace(/^>\s*(\d+)$/, '$1+')),
    decades,
    decadeMatrix: decadeMatrix
      .map((row) => ({ branch: branchDisplayName(row.branch ?? ''), counts: row.counts ?? [] }))
      .filter((row) => !empty.has(row.branch)),
    budapestShare: budapestShare ?? 0,
    points: points as [number, number][],
  };
}

export type BirthPlace = {
  city: string;
  country: string | null;
  lng: number;
  lat: number;
  people: { id: string; name: string; profession: string | null }[];
};

/** Every receipt of an award, with the creator and the age then. */
export type AwardAges = { awardId: number; award: string; ages: { id: string; age: number }[] };

export type CreatorStatistics = {
  generatedAt: string | null;
  birthDecades: { decade: number; alive: number; deceased: number }[];
  bornAbroadShare: number;
  countries: Ranked[];
  birthPlaces: BirthPlace[];
  /** The lower bounds of the five-year age bands. */
  ageBins: number[];
  /** Creations by the creator's age then, per branch; `counts` follows `ageBins`. */
  ageAtCreation: { branch: string; counts: number[]; total: number; peak: number }[];
  oldCreationShare: number;
  oldestWorkers: { name: string; age: number }[];
  ageAtAward: AwardAges[];
};

/**
 * The creators' part of the /felfedezes page. The counties, awards and schools still differ from
 * the story's rules and stay static for now, see docs/azopus-szamokban/backend-kerdesek.md.
 * Creation ages are calculated by the API and passed through here.
 */
export async function getCreatorStatistics(options?: RequestInit): Promise<CreatorStatistics> {
  const { data } = await statisticsGetCreators(options);
  const { birthDecades, bornAbroadShare, countries, birthPlaces, ageBins, ageAtCreation } = data;
  if (
    !birthDecades?.length ||
    bornAbroadShare === undefined ||
    !countries ||
    !birthPlaces ||
    !ageBins?.length ||
    !ageAtCreation?.length
  ) {
    throw new Error('Invalid API response: incomplete creator statistics');
  }

  return {
    generatedAt: data.generatedAt ?? null,
    birthDecades: birthDecades.map((row) => ({
      decade: row.decade ?? 0,
      alive: row.alive ?? 0,
      deceased: row.deceased ?? 0,
    })),
    bornAbroadShare,
    // One creator comes without a country, under a blank label.
    countries: toRanked(countries, (label) => label.trim()).filter((row) => row.label),
    birthPlaces: birthPlaces.flatMap((place) =>
      place.city && Number.isFinite(place.lng) && Number.isFinite(place.lat)
        ? [
            {
              city: place.city.trim(),
              country: place.country?.trim() || null,
              lng: place.lng as number,
              lat: place.lat as number,
              people: (place.people ?? []).map((person) => ({
                id: person.id ?? '',
                name: person.name ?? '',
                profession: person.profession || null,
              })),
            },
          ]
        : []
    ),
    ageBins,
    // A branch without dated creations has no peak; the story names the first and the last row as
    // the branches peaking earliest and latest, so the rows go by their peak.
    ageAtCreation: ageAtCreation
      .flatMap((row) =>
        row.branch && typeof row.peak === 'number' && row.total
          ? [
              {
                branch: branchDisplayName(row.branch),
                counts: row.counts ?? [],
                total: row.total,
                peak: row.peak,
              },
            ]
          : []
      )
      .sort((a, b) => a.peak - b.peak),
    oldCreationShare: data.oldCreationShare ?? 0,
    // The story names the first; the whole list (500+) is not needed.
    oldestWorkers: (data.oldestWorkers ?? [])
      .flatMap((row) => (row.name && row.age ? [{ name: row.name, age: row.age }] : []))
      .sort((a, b) => b.age - a.age)
      .slice(0, 6),
    // A few awards come without a name; they can't be told apart, so they stay out.
    ageAtAward: (data.ageAtAward ?? []).flatMap((row) =>
      typeof row.awardId === 'number' && row.award?.trim()
        ? [
            {
              awardId: row.awardId,
              award: row.award.trim(),
              ages: (row.ages ?? []).flatMap((item) =>
                item.id && typeof item.age === 'number' ? [{ id: item.id, age: item.age }] : []
              ),
            },
          ]
        : []
    ),
  };
}

/** A creator's card with one number on it. */
export type CreatorCard = {
  id: string;
  name: string;
  profession: string | null;
  image: number | null;
  died: string | null;
  value: number;
};

export type ProgramStatistics = {
  generatedAt: string | null;
  total: number;
  /** The calendar's first month, 'YYYY-MM'. */
  firstMonth: string;
  calendar: { month: string; value: number }[];
  /** Monday to Sunday. */
  weekdays: Ranked[];
  /** The start hours, the columns of `grid`. */
  hours: number[];
  /** Per weekday; `counts` follows `hours`. */
  grid: { label: string; counts: number[] }[];
  creators: { alive: number; aliveWithProgram: number; top: CreatorCard[] };
  legacy: { creators: number; programs: number; top: CreatorCard[] };
};

const toCards = (rows: CreatorCount[] = []) =>
  rows.flatMap((row) =>
    row.id && row.name
      ? [
          {
            id: row.id,
            name: row.name,
            profession: row.profession || null,
            image: row.image ?? null,
            died: row.died || null,
            value: row.value ?? 0,
          },
        ]
      : []
  );

/** The "Ma" part of the /felfedezes page: the program calendar. */
export async function getProgramStatistics(options?: RequestInit): Promise<ProgramStatistics> {
  const { data } = await statisticsGetPrograms(options);
  const { firstMonth, calendar, weekdays, hours, grid, creators, legacy } = data;
  if (!firstMonth || !calendar?.length || !weekdays?.length || !hours?.length || !grid?.length) {
    throw new Error('Invalid API response: incomplete program statistics');
  }
  // Programs announced for the months to come are in the calendar too; the chart ends this month.
  const thisMonth = new Date().toISOString().slice(0, 7);

  return {
    generatedAt: data.generatedAt ?? null,
    total: data.total ?? 0,
    firstMonth,
    calendar: calendar.flatMap((row) =>
      row.month && row.month <= thisMonth ? [{ month: row.month, value: row.value ?? 0 }] : []
    ),
    weekdays: toRanked(weekdays),
    hours,
    grid: grid.map((row) => ({ label: row.label ?? '', counts: row.counts ?? [] })),
    creators: {
      alive: creators?.alive ?? 0,
      aliveWithProgram: creators?.aliveWithProgram ?? 0,
      top: toCards(creators?.top),
    },
    legacy: {
      creators: legacy?.creators ?? 0,
      programs: legacy?.programs ?? 0,
      top: toCards(legacy?.top),
    },
  };
}

export type VideoStatistics = {
  generatedAt: string | null;
  /** Every published video of the database, and by type. */
  videos: { total: number; types: Ranked[] };
  /** The "Hogyan készült?" conversations, and the creations and creators they belong to. */
  conversations: { count: number; creations: number; creators: number };
  /** The playlists, and the creators who have a series of their own. */
  playlists: { count: number; series: { id: string; name: string }[] };
  /** Minutes and hours come from the editors until the video lengths are in the database. */
  youtube: { publishedVideos: number; minutes: number | null; conversationHours: number | null };
};

/** The "Hogyan készült?" part of the /felfedezes page. */
export async function getVideoStatistics(options?: RequestInit): Promise<VideoStatistics> {
  const { data } = await statisticsGetVideo(options);
  const { videos, conversations, playlists, youtube } = data;
  if (!videos || !conversations || !playlists || !youtube) {
    throw new Error('Invalid API response: incomplete video statistics');
  }

  return {
    generatedAt: data.generatedAt ?? null,
    videos: {
      total: videos.total ?? 0,
      // The API writes the types with a hyphen ("alkotás-videó"); the story says "alkotásvideó".
      types: toRanked(videos.types, (label) => label.replace(/-videó$/, 'videó')),
    },
    conversations: {
      count: conversations.count ?? 0,
      creations: conversations.creations ?? 0,
      creators: conversations.creators ?? 0,
    },
    playlists: {
      count: playlists.count ?? 0,
      series: (playlists.series ?? []).flatMap((item) =>
        item.id && item.name ? [{ id: item.id, name: item.name.trim() }] : []
      ),
    },
    youtube: {
      publishedVideos: youtube.publishedVideos ?? 0,
      minutes: youtube.minutes ?? null,
      conversationHours: youtube.conversationHours ?? null,
    },
  };
}
