• Create partial match results from partially-processed data before cancellation.

    Returns successfully-matched entries when batch processing is cancelled. Allows users to review partial progress.

    Parameters

    • mangaList: KenmeiManga[]

      Full list of Kenmei manga.

    • cachedResults: Record<number, AniListManga[]>

      Results fetched before cancellation.

    Returns MangaMatchResult[]

    Array of match results for successfully-processed manga.

    export function handleCancellationResults(
    mangaList: KenmeiManga[],
    cachedResults: Record<number, AniListManga[]>,
    ): MangaMatchResult[] {
    const results: MangaMatchResult[] = [];

    // Load existing match results to preserve statuses during cancellation
    const existingResults = getSavedMatchResults() || [];
    const existingById = new Map<string, MangaMatchResult>();
    const existingByTitle = new Map<string, MangaMatchResult>();

    for (const result of existingResults) {
    if (result.kenmeiManga.id) {
    existingById.set(
    String(result.kenmeiManga.id),
    result as MangaMatchResult,
    );
    }
    existingByTitle.set(
    result.kenmeiManga.title.toLowerCase(),
    result as MangaMatchResult,
    );
    }

    // Helper to get existing result by ID or title
    const getExistingResult = (
    manga: KenmeiManga,
    ): MangaMatchResult | undefined => {
    if (manga.id) {
    const byId = existingById.get(String(manga.id));
    if (byId) return byId;
    }
    return existingByTitle.get(manga.title.toLowerCase());
    };

    // Process whatever results we have so far
    for (let i = 0; i < mangaList.length; i++) {
    if (cachedResults[i]) {
    const manga = mangaList[i];
    const potentialMatches = cachedResults[i].map((anilistManga) => ({
    manga: anilistManga,
    confidence: calculateConfidence(manga.title, anilistManga),
    }));

    const newResult: MangaMatchResult = {
    kenmeiManga: manga,
    anilistMatches: potentialMatches,
    selectedMatch:
    potentialMatches.length > 0 ? potentialMatches[0].manga : undefined,
    status: "pending",
    };

    // Preserve status from existing result if it's not "pending"
    const existingResult = getExistingResult(manga);
    if (existingResult?.status && existingResult.status !== "pending") {
    newResult.status = existingResult.status;
    newResult.selectedMatch = existingResult.selectedMatch;
    newResult.matchDate = existingResult.matchDate;
    }

    results.push(newResult);
    }
    }

    return results;
    }