import type { SupportedLanguage } from "../locales";
import type { EBookListItem } from "../types/book";
import { deriveReadingStatus, normalizeProgressPercent } from "./libraryStatus";
import { filterSubjectsByLocale } from "./subjectLocale";

export type EbookLibraryItem = {
  id: number;
  title: string;
  author: string;
  genre: string;
  subjects: string[];
  format: string;
  reading_status: string;
  reading_status_display: string;
  cover_image: string | null;
  progressPercent: number | null;
};

export function subjectsFromMetadata(
  metadata: Record<string, unknown> | undefined,
  locale?: SupportedLanguage,
): string[] {
  const ol = metadata?.openlibrary;
  if (!ol || typeof ol !== "object") return [];
  const subjects = (ol as { subjects?: unknown }).subjects;
  if (!Array.isArray(subjects)) return [];
  const raw = subjects.filter((s): s is string => typeof s === "string" && s.trim().length > 0).map((s) => s.trim());
  return locale ? filterSubjectsByLocale(raw, locale) : raw;
}

export function mapEbookToLibraryItem(e: EBookListItem, locale?: SupportedLanguage): EbookLibraryItem {
  const raw = e.subjects ?? [];
  const subjects = locale ? filterSubjectsByLocale(raw, locale) : raw;
  const reading_status = deriveReadingStatus(e.progress, Boolean(e.started));
  const progressPercent = normalizeProgressPercent(e.progress, reading_status);
  return {
    id: e.id,
    title: e.title,
    author: e.author,
    genre: subjects[0] ?? "",
    subjects,
    format: e.format,
    reading_status,
    reading_status_display: reading_status,
    cover_image: e.cover_image,
    progressPercent,
  };
}

export function ebookMatchesQuery(item: Pick<EbookLibraryItem, "title" | "author" | "subjects">, query: string): boolean {
  const q = query.trim().toLowerCase();
  if (!q) return true;
  if (item.title.toLowerCase().includes(q)) return true;
  if (item.author.toLowerCase().includes(q)) return true;
  return item.subjects.some((s) => s.toLowerCase().includes(q));
}

export function collectGenresFromEbooks(ebooks: EBookListItem[], locale: SupportedLanguage): string[] {
  const set = new Set<string>();
  for (const e of ebooks) {
    for (const s of filterSubjectsByLocale(e.subjects ?? [], locale)) set.add(s);
  }
  return [...set].sort((a, b) => a.localeCompare(b, locale));
}

export function collectAuthorsFromEbooks(ebooks: EBookListItem[]): string[] {
  const set = new Set<string>();
  for (const e of ebooks) {
    if (e.author?.trim()) set.add(e.author.trim());
  }
  return [...set].sort((a, b) => a.localeCompare(b));
}
