import type { DebugPublishMeta } from '../../utils/debugPublish';
import { inferGradeFromAge } from '../../utils/debugPublish';
import { MATH_WORKSHEET_DEFINITIONS } from '../../config/worksheets/math';

export { MATH_WORKSHEET_DEFINITIONS };

type MathWorksheetDefinitionItem = (typeof MATH_WORKSHEET_DEFINITIONS)[number];

const MATH_WORKSHEET_BY_ID = Object.fromEntries(
    MATH_WORKSHEET_DEFINITIONS.map((item) => [item.id, item]),
) as Record<string, MathWorksheetDefinitionItem>;

function resolveMathPublishId(
    routeId: string,
    selectedTypeId: string,
    mode?: string,
): string {
    if (selectedTypeId === 'addition') {
        return mode || 'addition-5';
    }

    if (selectedTypeId === 'number-object-match' && mode === 'fill') {
        return 'number-object-fill';
    }

    if (routeId in MATH_WORKSHEET_BY_ID) {
        return routeId;
    }

    return selectedTypeId;
}

export function getPublishMetaByMathState(
    routeId: string,
    selectedTypeId: string,
    mode?: string,
): DebugPublishMeta | null {
    const id = resolveMathPublishId(routeId, selectedTypeId, mode);
    const item = MATH_WORKSHEET_BY_ID[id];
    if (!item) return null;

    return {
        id: item.id,
        title: item.title,
        subtitle: item.subtitle,
        category: 'math',
        subcategory: 'math-draw',
        path: `/mathPages/mathDraw/mathDraw?id=${item.id}`,
        ageMin: item.ageMin,
        ageMax: item.ageMax,
        grade: inferGradeFromAge(item.ageMin, item.ageMax),
        difficulty: item.difficulty,
        previewImg: '',
        tags: [...item.tags],
        isNew: false,
        isHot: false,
        sortOrder: item.sortOrder,
        status: 'draft',
    };
}
