import { query } from './db'; import { ensureAnalysisSchema } from './analysis-schema'; import type { ArticleData, Block, Section } from './article-types'; /** Analysis articles about one paper, looked up by the paper's stable key (conf, ext_id). */ export async function getArticlesFor(conf: string, extId: string | null): Promise { if (!extId) return []; try { await ensureAnalysisSchema(); const articles = await query<{ id: number; slug: string; title: string; summary: string | null; revision: number; updated_at: Date }>( `SELECT id, slug, title, summary, revision, updated_at FROM analysis.article WHERE subject_conf = ? AND subject_ext_id = ? ORDER BY created_at, id`, [conf, extId]); if (!articles.length) return []; const ids = articles.map((a) => a.id); const [secs, blocks, links] = await Promise.all([ query<{ id: number; article_id: number; parent_id: number | null; key: string; title: string; level: number; position: number }>( `SELECT id, article_id, parent_id, key, title, level, position FROM analysis.section WHERE article_id = ANY(?) ORDER BY position, id`, [ids]), query<{ section_id: number; type: Block['type']; data: Block['data'] }>( `SELECT b.section_id, b.type, b.data FROM analysis.block b JOIN analysis.section s ON s.id = b.section_id WHERE s.article_id = ANY(?) ORDER BY b.position`, [ids]), query<{ article_id: number; kind: string; title: string; url: string; note: string | null }>( `SELECT article_id, kind, title, url, note FROM analysis.link WHERE article_id = ANY(?) ORDER BY position, id`, [ids]), ]); const bySection = new Map(); for (const b of blocks) (bySection.get(b.section_id) ?? bySection.set(b.section_id, []).get(b.section_id)!).push({ type: b.type, data: b.data } as Block); const node = new Map(); for (const s of secs) node.set(s.id, { key: s.key, title: s.title, level: s.level, blocks: bySection.get(s.id) ?? [], children: [], _parent: s.parent_id, _article: s.article_id }); const roots = new Map(); for (const s of secs) { const n = node.get(s.id)!; if (n._parent && node.has(n._parent)) node.get(n._parent)!.children.push(n); else (roots.get(s.article_id) ?? roots.set(s.article_id, []).get(s.article_id)!).push(n); } return articles.map((a) => ({ slug: a.slug, title: a.title, summary: a.summary, revision: a.revision, updatedAt: new Date(a.updated_at).toISOString().slice(0, 10), sections: roots.get(a.id) ?? [], links: links.filter((l) => l.article_id === a.id).map(({ kind, title, url, note }) => ({ kind, title, url, note })), })); } catch { return []; // database not reachable or schema not creatable: show the paper without articles } }