import type { DebugPublishMeta } from '../../utils/debugPublish';
import { inferGradeFromAge } from '../../utils/debugPublish';
import {
    CLOCK_READING_WORKSHEET_DEFINITIONS,
    CLOCK_CONNECT_WORKSHEET_DEFINITIONS,
} from '../../config/worksheets/clock';

export { CLOCK_READING_WORKSHEET_DEFINITIONS, CLOCK_CONNECT_WORKSHEET_DEFINITIONS };

/** 合并所有钟表类 worksheet 定义 */
const ALL_CLOCK_DEFINITIONS = [
    ...CLOCK_READING_WORKSHEET_DEFINITIONS,
    ...CLOCK_CONNECT_WORKSHEET_DEFINITIONS,
];

type ClockWorksheetRow = (typeof ALL_CLOCK_DEFINITIONS)[number];

const CLOCK_WORKSHEET_BY_ID = Object.fromEntries(
    ALL_CLOCK_DEFINITIONS.map((m) => [m.id, m]),
) as Record<string, ClockWorksheetRow>;

/** 时刻类型选项（顺序：随机、整点、半点、刻钟） */
export const CLOCK_TIME_MODE_OPTIONS = [
    { id: 'random' as const, label: '随机', subtitle: '0–59 分均可' },
    { id: 'whole-hour' as const, label: '整点', subtitle: '如 3:00' },
    { id: 'half-hour' as const, label: '半点', subtitle: '如 6:30' },
    { id: 'quarter-hour' as const, label: '刻钟', subtitle: '如 2:15、7:45' },
];

export type ClockTimeMode = (typeof CLOCK_TIME_MODE_OPTIONS)[number]['id'];

/** 练习类型选项（顺序：认识时钟、时钟连线） */
export const CLOCK_EXERCISE_TYPE_OPTIONS = [
    { id: 'clock-reading' as const, label: '认识时钟', subtitle: '看钟写时间' },
    { id: 'clock-connect' as const, label: '时钟连线', subtitle: '钟表连对应时间' },
];

export type ClockExerciseType = (typeof CLOCK_EXERCISE_TYPE_OPTIONS)[number]['id'];

export function getModeInfo(id: string) {
    const m = CLOCK_WORKSHEET_BY_ID[id];
    return m ? { title: m.title, desc: m.subtitle } : undefined;
}

export function isValidMode(id: string): boolean {
    return id in CLOCK_WORKSHEET_BY_ID;
}

export function getPublishMetaByMode(id: string): DebugPublishMeta | null {
    const m = CLOCK_WORKSHEET_BY_ID[id];
    if (!m) return null;
    return {
        id: m.id,
        title: m.title,
        subtitle: m.subtitle,
        category: 'math',
        subcategory: 'clock',
        path: `/mathPages/clockReading/clockReading?id=${m.id}`,
        ageMin: m.ageMin,
        ageMax: m.ageMax,
        grade: inferGradeFromAge(m.ageMin, m.ageMax),
        difficulty: m.difficulty,
        previewImg: '',
        tags: [...m.tags],
        isNew: false,
        isHot: false,
        sortOrder: m.sortOrder,
        status: 'draft',
    };
}
