/* ============================================================
   data.js — 중앙 데이터 로더 (모든 JSON 산출물)
   ============================================================ */
(function (global) {
  'use strict';

  const Store = {
    catalog: null,      // protein_catalog.json
    scenarios: null,    // twin_scenarios.json
    graph: null,        // knowledge_graph.json
    papersIdx: null,    // papers_index.json
    extras: null,       // extras.json (prior_art, new_papers, frameworks)
    analysis: null,     // ../analysis_results.json (기존 통계/라이브러리)
    calibration: null,  // calibration_result.json (COPASI 정량 보정)
    coupled: null,      // coupled_scenarios.json (cycle↔chronic COMBINE)
    proteinByGene: {},
  };

  async function loadJSON(url, fallback) {
    try {
      const r = await fetch(url, { cache: 'no-store' });
      if (!r.ok) throw new Error(r.status);
      return await r.json();
    } catch (e) {
      console.warn('load 실패:', url, e.message);
      return fallback;
    }
  }

  async function loadAll() {
    const [catalog, scenarios, graph, papersIdx, extras, analysis, calibration] = await Promise.all([
      loadJSON('data/protein_catalog.json', { proteins: [] }),
      loadJSON('data/twin_scenarios.json', { scenarios: [], interventions: {}, diseases: {} }),
      loadJSON('data/knowledge_graph.json', { nodes: [], links: [], summary: {} }),
      loadJSON('data/papers_index.json', {}),
      loadJSON('data/extras.json', { new_papers: [], prior_art: [], frameworks: [] }),
      loadJSON('../analysis_results.json', { papers: [], stats: {} }),
      loadJSON('data/calibration_result.json', null),
    ]);
    Store.coupled = await loadJSON('data/coupled_scenarios.json', null);
    Store.validation = await loadJSON('data/validation_report.json', null);
    Store.catalog = catalog;
    Store.scenarios = scenarios;
    Store.graph = graph;
    Store.papersIdx = papersIdx;
    Store.extras = extras;
    Store.analysis = analysis;
    Store.calibration = calibration;
    (catalog.proteins || []).forEach(p => { Store.proteinByGene[p.gene] = p; });
    return Store;
  }

  // 시나리오 조회 (정확한 disease + interventions 조합)
  function findScenario(disease, interventions) {
    const id = `${disease}|${(interventions || []).join('+')}`;
    return (Store.scenarios.scenarios || []).find(s => s.id === id);
  }

  Store.loadAll = loadAll;
  Store.findScenario = findScenario;
  global.Store = Store;
})(window);
