// ═══════════════════════════════════════════════════════════
//  知識庫載入器
//  讀 data/knowledge.json（課綱輕量包）與 data/notes.json（全文）
//  進記憶體。由 scripts/build-knowledge.mjs 從 ../emmy 產生。
// ═══════════════════════════════════════════════════════════
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const DATA_DIR = path.join(__dirname, '..', 'data');
const KNOWLEDGE_PATH = path.join(DATA_DIR, 'knowledge.json');
const NOTES_PATH = path.join(DATA_DIR, 'notes.json');

let _knowledge = null;
let _notes = null;

export function knowledgeReady() {
  return fs.existsSync(KNOWLEDGE_PATH) && fs.existsSync(NOTES_PATH);
}

export function getKnowledge() {
  if (_knowledge) return _knowledge;
  if (!fs.existsSync(KNOWLEDGE_PATH)) return null;
  _knowledge = JSON.parse(fs.readFileSync(KNOWLEDGE_PATH, 'utf8'));
  return _knowledge;
}

export function getNote(kind, id) {
  if (!_notes) {
    if (!fs.existsSync(NOTES_PATH)) return null;
    _notes = JSON.parse(fs.readFileSync(NOTES_PATH, 'utf8'));
  }
  return _notes[`${kind}:${id}`] || null;
}

// 給 fincheck 用：心法/名詞/案例的 linkMap，方便把檢查結果連回筆記
export function getLinkMap() {
  const k = getKnowledge();
  return (k && k.linkMap) || {};
}
