false, 'error'=>'PG connection failed']); exit; } switch ($action) { case 'list': $sql = "SELECT id, ts, opus_id, decision_type, topic, decision, impact, status, tags FROM wevia_decisions"; $conditions = []; $params = []; $i = 1; if ($topic) { $conditions[] = "topic ILIKE \$$i"; $params[] = '%' . $topic . '%'; $i++; } if ($opus) { $conditions[] = "opus_id = \$$i"; $params[] = $opus; $i++; } if ($conditions) $sql .= " WHERE " . implode(" AND ", $conditions); $sql .= " ORDER BY ts DESC LIMIT " . $limit; $r = @pg_query_params($conn, $sql, $params); $items = []; if ($r) while ($row = pg_fetch_assoc($r)) $items[] = $row; echo json_encode(['ok'=>true, 'action'=>'list', 'count'=>count($items), 'items'=>$items], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); break; case 'summary': $stats_sql = "SELECT COUNT(*) as total, COUNT(*) FILTER (WHERE status = 'active') as active, COUNT(DISTINCT opus_id) as opus_count, COUNT(DISTINCT topic) as topics_count, COUNT(*) FILTER (WHERE impact = 'critical') as critical, COUNT(*) FILTER (WHERE impact = 'high') as high FROM wevia_decisions"; $r = @pg_query($conn, $stats_sql); $stats = $r ? pg_fetch_assoc($r) : []; $by_opus_sql = "SELECT opus_id, COUNT(*) as n FROM wevia_decisions GROUP BY opus_id ORDER BY n DESC"; $r = @pg_query($conn, $by_opus_sql); $by_opus = []; if ($r) while ($row = pg_fetch_assoc($r)) $by_opus[] = $row; $latest_sql = "SELECT topic, opus_id, impact, ts FROM wevia_decisions ORDER BY ts DESC LIMIT 5"; $r = @pg_query($conn, $latest_sql); $latest = []; if ($r) while ($row = pg_fetch_assoc($r)) $latest[] = $row; echo json_encode([ 'ok' => true, 'action' => 'summary', 'stats' => $stats, 'by_opus' => $by_opus, 'latest' => $latest, ], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); break; default: echo json_encode(['ok'=>false, 'error'=>'Unknown action · use list|summary']); } pg_close($conn);