/**
 * Risk assignment / report tables: columns follow form section order.
 * Same question_id may appear in multiple sections — use composite keys so each RPN (and every question) has its own column and cell.
 */

/**
 * One column per question per section (schema order). colKey = `${sectionIndex}:${question_id}`.
 * @param {object|null} formSchema
 * @returns {Array<{ colKey: string, sectionIndex: number, question_id: number, label: string }>}
 */
export function buildDynamicColumns(formSchema) {
  if (!formSchema?.sections) return [];
  const cols = [];
  for (let sectionIndex = 0; sectionIndex < formSchema.sections.length; sectionIndex++) {
    const sec = formSchema.sections[sectionIndex];
    for (const q of sec.questions || []) {
      const qid = Number(q.question_id);
      if (!Number.isFinite(qid)) continue;
      cols.push({
        colKey: `${sectionIndex}:${qid}`,
        sectionIndex,
        question_id: qid,
        label: q.question || `Q${qid}`
      });
    }
  }
  return cols;
}

/**
 * @param {object} t - parsed snap_timing JSON
 * @returns {{ byCol: Map<string,string>, byQid: Map<number,string>, violationTime: string }}
 */
export function extractAnswerMapsFromTiming(t) {
  const violationTime = t?.risk_violation_time || '—';
  const byCol = new Map();
  const byQid = new Map();
  const instances = t?.section_instances || [];
  instances.forEach((inst, sectionIndex) => {
    const ans = inst.answers || {};
    for (const [qidStr, val] of Object.entries(ans)) {
      if (val === undefined || val === null || val === '') continue;
      const qid = Number(qidStr);
      if (!Number.isFinite(qid)) continue;
      const s = String(val);
      byCol.set(`${sectionIndex}:${qid}`, s);
      byQid.set(qid, s);
    }
  });
  return { byCol, byQid, violationTime };
}

/**
 * Prefer composite key (section instance index aligns with schema section order); fallback to question_id-only for older snaps.
 */
export function resolveCellRaw(byCol, byQid, col) {
  const ck = col.colKey;
  if (byCol.has(ck)) {
    const v = byCol.get(ck);
    if (v !== undefined && v !== null && String(v).trim() !== '') return String(v);
  }
  const legacy = byQid.get(col.question_id);
  if (legacy != null && String(legacy).trim() !== '') return String(legacy);
  return null;
}
