import { readFileSync } from "node:fs"; import { join, normalize } from "node:path"; export interface SourceRef { file_name: string; book?: string; printed_page?: number; pdf_page?: number; } export interface SyllabusTopic { topic_title: string; status: string; source_refs: SourceRef[]; } export interface SyllabusChapter { chapter_no: number; chapter_title: string; discipline: string; book: string; printed_pages: string; source_file: string; topics_status: string; topics_note?: string; topics: SyllabusTopic[]; topics_seed?: unknown[]; } export interface SyllabusPart { part_name: string; chapter_count: number; chapters: SyllabusChapter[]; } export interface SyllabusMap { board: string; year: string; class: string; subject: string; books: string[]; curation_status: { curated: string; pending_curated_read: string; }; discipline_note?: string; parts: SyllabusPart[]; } export interface ChapterIndexEntry { chapter_id: string; chapter_no: number; chapter_title: string; discipline: string; part: string; book: string; source_file: string; source_id: string; pdf_start_page: number; pdf_end_page: number; printed_start_page: number; printed_end_page: number; page_count: number; confidence: number; needs_review: boolean; needs_review_pages_pdf: number[]; detection_evidence: string; folder: string; } export interface ChapterIndexFile { board: string; class: string; subject: string; year: string; total_chapters: number; chapters: ChapterIndexEntry[]; } export interface ChapterSummary extends ChapterIndexEntry { board: string; class: string; subject: string; year: string; } export interface SslcChapterMap { chapter_id: string; chapter_no: number; chapter_title: string; discipline: string; book: string; source_file: string; pdf_pages: string; printed_pages: string; source: string; generation_policy: string; main_topics: Array<{ topic: string; printed_pages: number[]; points: string[]; }>; key_dates?: Record; needs_review_notes?: string; } export interface DailyMission { mission_title: string; chapter: string; topic: string; estimated_time: string; learning_goal: string; five_key_notes: string[]; lesson_script_outline: string[]; visual_frame_ideas: string[]; quiz_question_ids: string[]; answer_correction_rule_ids: string[]; weak_area_tags: string[]; revision_task: string; next_mission: string; source_refs: SourceRef[]; } export interface DailyMissionsFile { chapter_id: string; chapter_title: string; source_file: string; missions: DailyMission[]; } export interface SslcQuestion { id: string; type: string; marks: number; question: string; answer_outline: string; keywords: string[]; difficulty: string; status: string; source_refs: SourceRef[]; options?: string[]; answer?: string; } export interface PossibleQuestionsFile { chapter_id: string; chapter_title: string; source_file: string; book: string; policy: string; total_questions: number; by_type: Record; questions: SslcQuestion[]; } export interface Flashcard { front: string; back: string; type: string; status: string; source_refs: SourceRef[]; marks?: number; } export interface FlashcardsFile { flashcards: unknown[]; chapter_id: string; chapter_title: string; source_file: string; cards: Flashcard[]; } export interface DefinitionItem { term: string; definition: string; status: string; source_refs: SourceRef[]; } export interface DefinitionsFile { chapter_id: string; chapter_title: string; source_file: string; note?: string; definitions: DefinitionItem[]; } export interface AnswerCorrectionRule { id: string; applies_to: string[]; rule: string; source_refs: SourceRef[]; keyword_map?: Record; } export interface AnswerCorrectionRulesFile { chapter_id: string; chapter_title: string; source_file: string; rules: AnswerCorrectionRule[]; } export interface QuestionFilters { type?: string; marks?: number; difficulty?: string; status?: string; missionId?: string; ids?: string[]; } export interface ChapterLookup { chapterId?: string; discipline?: string; chapterNo?: number; chapterTitle?: string; } export interface MissionStudyBundle { chapter: ChapterSummary; mission_id: string; mission_title: string; lesson_goal: string; five_key_notes: string[]; quiz_questions: SslcQuestion[]; flashcards: Flashcard[]; weak_area_tags: string[]; source_refs: SourceRef[]; answer_correction_rules: AnswerCorrectionRule[]; mission: DailyMission; formulas?: unknown[]; derivations?: unknown[]; numericalPatterns?: unknown[]; visualLessonFrames?: unknown[]; } export interface KnowledgeBaseValidationResult { chapters: number; questions: number; flashcards: number; definitions: number; missingSourceRefs: string[]; needsReviewCount: number; } interface ChapterBundle { summary: ChapterSummary; chapterMap: SslcChapterMap; missions: DailyMissionsFile; questions: PossibleQuestionsFile; flashcards: { flashcards: unknown[] }; definitions: DefinitionsFile; answerCorrectionRules: AnswerCorrectionRulesFile; formulas: { formulas: unknown[] }; derivations: { derivations: unknown[] }; numericalPatterns: { patterns: unknown[] }; visualLessonFrames: { frames: unknown[] }; } interface KnowledgeBaseCache { syllabusMap: SyllabusMap; chapterIndex: ChapterIndexFile; chaptersById: Map; } const DATASET_ROOT = join(process.cwd(), "outputs", "sslc-physics-2025"); const REQUIRED_CHAPTER_FILES = { chapterMap: "chapter_map.json", missions: "daily_missions.json", questions: "possible_questions.json", flashcards: "flashcards.json", definitions: "definitions.json", answerCorrectionRules: "answer_correction_rules.json", formulas: "formulas.json", derivations: "derivations.json", numericalPatterns: "numerical_patterns.json", visualLessonFrames: "visual_lesson_frames.json", } as const; let cache: KnowledgeBaseCache | null = null; function readJsonFile(...pathParts: string[]): T { const filePath = join(DATASET_ROOT, ...pathParts); const normalizedPath = normalize(filePath); if (!normalizedPath.startsWith(normalize(DATASET_ROOT))) { throw new Error(`Refusing to read outside SSLC dataset: ${filePath}`); } return JSON.parse(readFileSync(normalizedPath, "utf8")) as T; } function loadKnowledgeBase(): KnowledgeBaseCache { if (cache) { return cache; } const syllabusMap = readJsonFile("syllabus_map.json"); const rawChapterIndex = readJsonFile("physics_subject_index.json"); // physics_subject_index.json ships a lean shape (`title`, `global_chapter_no`) // instead of the `ChapterIndexEntry` shape the rest of this module expects // (`chapter_title`, `chapter_no`) — normalize here so every downstream // consumer (getChapters, getSubjects, resolveChapterId) sees real values // instead of `undefined`. const chapterIndex: ChapterIndexFile = { ...rawChapterIndex, chapters: rawChapterIndex.chapters.map((entry) => { const raw = entry as ChapterIndexEntry & { title?: string; global_chapter_no?: number }; return { ...raw, chapter_title: raw.chapter_title ?? raw.title ?? "", chapter_no: raw.chapter_no ?? raw.global_chapter_no ?? 0, discipline: raw.discipline ?? "", }; }), }; const chaptersById = new Map(); for (const entry of chapterIndex.chapters) { const summary: ChapterSummary = { ...entry, board: chapterIndex.board, class: chapterIndex.class, subject: chapterIndex.subject, year: chapterIndex.year, }; const bundle: ChapterBundle = { summary, chapterMap: readJsonFile(entry.folder, REQUIRED_CHAPTER_FILES.chapterMap), missions: readJsonFile(entry.folder, REQUIRED_CHAPTER_FILES.missions), questions: readJsonFile(entry.folder, REQUIRED_CHAPTER_FILES.questions), flashcards: readJsonFile(entry.folder, REQUIRED_CHAPTER_FILES.flashcards), definitions: readJsonFile(entry.folder, REQUIRED_CHAPTER_FILES.definitions), answerCorrectionRules: readJsonFile( entry.folder, REQUIRED_CHAPTER_FILES.answerCorrectionRules, ), formulas: readJsonFile<{ formulas: unknown[] }>(entry.folder, REQUIRED_CHAPTER_FILES.formulas), derivations: readJsonFile<{ derivations: unknown[] }>(entry.folder, REQUIRED_CHAPTER_FILES.derivations), numericalPatterns: readJsonFile<{ patterns: unknown[] }>(entry.folder, REQUIRED_CHAPTER_FILES.numericalPatterns), visualLessonFrames: readJsonFile<{ frames: unknown[] }>(entry.folder, REQUIRED_CHAPTER_FILES.visualLessonFrames), }; chaptersById.set(entry.chapter_id, bundle); } cache = { syllabusMap, chapterIndex, chaptersById }; return cache; } function clone(value: T): T { return JSON.parse(JSON.stringify(value)) as T; } function normalizeText(value: string): string { return value.trim().toLowerCase().replace(/\s+/g, " "); } function normalizeMissionId(value: string): string { const trimmed = value.trim().toUpperCase(); const numeric = trimmed.match(/\d+/)?.[0]; if (numeric) { return `M${numeric}`; } return trimmed; } function getMissionId(mission: DailyMission): string { return mission.mission_title.match(/^M\d+/i)?.[0].toUpperCase() ?? normalizeMissionId(mission.mission_title); } function getSourceKey(ref: SourceRef): string { return [ref.file_name, ref.book ?? "", ref.printed_page ?? "", ref.pdf_page ?? ""].join("|"); } function hasSourceOverlap(itemRefs: SourceRef[], missionRefs: SourceRef[]): boolean { const missionKeys = new Set(missionRefs.map(getSourceKey)); const missionPages = new Set(missionRefs.map((ref) => `${ref.file_name}|${ref.book ?? ""}|${ref.printed_page ?? ""}`)); return itemRefs.some((ref) => { const exactKey = getSourceKey(ref); const printedPageKey = `${ref.file_name}|${ref.book ?? ""}|${ref.printed_page ?? ""}`; return missionKeys.has(exactKey) || missionPages.has(printedPageKey); }); } function getChapterBundle(chapterId: string): ChapterBundle | null { return loadKnowledgeBase().chaptersById.get(chapterId) ?? null; } export function getSyllabusMap(): SyllabusMap { return clone(loadKnowledgeBase().syllabusMap); } export function getBoards() { const { syllabusMap } = loadKnowledgeBase(); return [ { id: "kerala-sslc-2025", board: syllabusMap.board, class: syllabusMap.class, year: syllabusMap.year, subjects: [syllabusMap.subject], books: [...[]], }, ]; } export function getSubjects() { const { syllabusMap, chapterIndex } = loadKnowledgeBase(); const disciplines = Array.from(new Set(chapterIndex.chapters.map((chapter) => chapter.discipline))).sort(); return [ { id: "physics", name: syllabusMap.subject, board: syllabusMap.board, class: syllabusMap.class, year: syllabusMap.year, disciplines, }, ]; } export function getChapters(filters: { discipline?: string } = {}): ChapterSummary[] { const { chapterIndex } = loadKnowledgeBase(); const discipline = filters.discipline ? normalizeText(filters.discipline) : null; return chapterIndex.chapters .filter((chapter) => !discipline || normalizeText(chapter.discipline) === discipline) .map((chapter) => clone({ ...chapter, board: chapterIndex.board, class: chapterIndex.class, subject: chapterIndex.subject, year: chapterIndex.year, }), ); } export function resolveChapterId(lookup: ChapterLookup): string | null { if (lookup.chapterId && getChapterBundle(lookup.chapterId)) { return lookup.chapterId; } const discipline = lookup.discipline ? normalizeText(lookup.discipline) : null; const title = lookup.chapterTitle ? normalizeText(lookup.chapterTitle) : null; const chapter = getChapters().find((item) => { const disciplineMatches = !discipline || normalizeText(item.discipline) === discipline; const chapterNoMatches = lookup.chapterNo === undefined || item.chapter_no === lookup.chapterNo; const titleMatches = !title || normalizeText(item.chapter_title) === title; return disciplineMatches && chapterNoMatches && titleMatches; }); return chapter?.chapter_id ?? null; } export function getChapterMap(chapterId: string): SslcChapterMap | null { const bundle = getChapterBundle(chapterId); return bundle ? clone(bundle.chapterMap) : null; } export function getDailyMissions(chapterId: string): DailyMission[] { const bundle = getChapterBundle(chapterId); return bundle ? clone(bundle.missions.missions) : []; } export interface MissionSummary { mission_id: string; mission_title: string; } export function getMissionSummaries(chapterId: string): MissionSummary[] { return getDailyMissions(chapterId).map((mission) => ({ mission_id: getMissionId(mission), mission_title: mission.mission_title, })); } export function getQuestions(chapterId: string, filters: QuestionFilters = {}): SslcQuestion[] { const bundle = getChapterBundle(chapterId); if (!bundle) { return []; } const missionQuestionIds = filters.missionId ? getDailyMissions(chapterId).find((mission) => getMissionId(mission) === normalizeMissionId(filters.missionId ?? "")) ?.quiz_question_ids : null; const requestedIds = new Set([...(filters.ids ?? []), ...(missionQuestionIds ?? [])]); return clone( bundle.questions.questions.filter((question) => { const typeMatches = !filters.type || normalizeText(question.type) === normalizeText(filters.type); const marksMatches = filters.marks === undefined || question.marks === filters.marks; const difficultyMatches = !filters.difficulty || normalizeText(question.difficulty) === normalizeText(filters.difficulty); const statusMatches = !filters.status || normalizeText(question.status) === normalizeText(filters.status); const idMatches = requestedIds.size === 0 || requestedIds.has(question.id); return typeMatches && marksMatches && difficultyMatches && statusMatches && idMatches; }), ); } export function getFlashcards(chapterId: string): Flashcard[] { const bundle = getChapterBundle(chapterId); return bundle ? clone((bundle.flashcards as { flashcards: Flashcard[] }).flashcards) : []; } export function getDefinitions(chapterId: string): DefinitionItem[] { const bundle = getChapterBundle(chapterId); return bundle ? clone(bundle.definitions.definitions) : []; } export function getAnswerCorrectionRules(chapterId: string): AnswerCorrectionRule[] { const bundle = getChapterBundle(chapterId); return bundle ? clone(bundle.answerCorrectionRules.rules) : []; } export function getMission(chapterId: string, missionId: string): MissionStudyBundle | null { const bundle = getChapterBundle(chapterId); if (!bundle) { return null; } const normalizedMissionId = normalizeMissionId(missionId); const mission = bundle.missions.missions.find((candidate) => getMissionId(candidate) === normalizedMissionId); if (!mission) { return null; } const quizQuestionIds = new Set(mission.quiz_question_ids); const answerRuleIds = new Set(mission.answer_correction_rule_ids); const flashcardsCasted = (bundle.flashcards as { flashcards: Flashcard[] }).flashcards; const matchingFlashcards = flashcardsCasted.filter((card) => hasSourceOverlap(card.source_refs, mission.source_refs)); const missionFlashcards = matchingFlashcards.length > 0 ? matchingFlashcards : flashcardsCasted.slice(0, 5); return clone({ chapter: bundle.summary, mission_id: getMissionId(mission), mission_title: mission.mission_title, lesson_goal: mission.learning_goal, five_key_notes: mission.five_key_notes, quiz_questions: bundle.questions.questions.filter((question) => quizQuestionIds.has(question.id)), flashcards: missionFlashcards, weak_area_tags: mission.weak_area_tags, source_refs: mission.source_refs, answer_correction_rules: bundle.answerCorrectionRules.rules.filter((rule) => answerRuleIds.has(rule.id)), mission, formulas: bundle.formulas ? bundle.formulas.formulas : undefined, derivations: bundle.derivations ? bundle.derivations.derivations : undefined, numericalPatterns: bundle.numericalPatterns ? bundle.numericalPatterns.patterns : undefined, visualLessonFrames: bundle.visualLessonFrames ? bundle.visualLessonFrames.frames : undefined, }); } export function validateKnowledgeBase(): KnowledgeBaseValidationResult { const { chapterIndex, chaptersById } = loadKnowledgeBase(); const missingSourceRefs: string[] = []; let questions = 0; let flashcards = 0; let definitions = 0; let needsReviewCount = 0; for (const [chapterId, bundle] of chaptersById.entries()) { if (bundle.summary.needs_review) { needsReviewCount += 1; } for (const mission of bundle.missions.missions) { if (!mission.source_refs?.length) { missingSourceRefs.push(`${chapterId}:mission:${mission.mission_title}`); } } for (const question of bundle.questions.questions) { questions += 1; if (!question.source_refs?.length) { missingSourceRefs.push(`${chapterId}:question:${question.id}`); } } for (const card of (bundle.flashcards as { flashcards: Flashcard[] }).flashcards) { flashcards += 1; if (!card.source_refs?.length) { missingSourceRefs.push(`${chapterId}:flashcard:${card.front}`); } } for (const definition of bundle.definitions.definitions) { definitions += 1; if (!definition.source_refs?.length) { missingSourceRefs.push(`${chapterId}:definition:${definition.term}`); } } for (const rule of bundle.answerCorrectionRules.rules) { if (!rule.source_refs?.length) { missingSourceRefs.push(`${chapterId}:answerRule:${rule.id}`); } } } return { chapters: chapterIndex.chapters.length, questions, flashcards, definitions, missingSourceRefs, needsReviewCount, }; } export function getFormulas(chapterId: string) { return getChapterBundle(chapterId)?.formulas?.formulas || null; } export function getDerivations(chapterId: string) { return getChapterBundle(chapterId)?.derivations?.derivations || null; } export function getNumericalPatterns(chapterId: string) { return getChapterBundle(chapterId)?.numericalPatterns?.patterns || null; } export function getVisualLessonFrames(chapterId: string) { return getChapterBundle(chapterId)?.visualLessonFrames?.frames || null; }