// lib/process/util.js — small shared helpers for the process engine.
//
// Consolidates helpers that were duplicated across engine.js, definitions.js,
// stages/agent-run.js, definition-settings.js, and app/workflows/page.js.

export function safeJson(value, fallback = null) {
  if (!value) return fallback;
  try { return JSON.parse(value); } catch { return fallback; }
}

// Pick the most "branded" colour from a brand profile — first colour whose
// name suggests an accent (Mars / Accent / Primary / Brand / Red / Orange /
// Coral), else first non-neutral. Falls back to Mars red.
const ACCENT_NAME_PATTERN = /mars|accent|primary|brand|red|orange|coral/i;
const NEUTRAL_PATTERN = /^#?(ffffff|000000|fff|0f0f11|111318|1a1817|f7f4ee|e8e8e5|dcdcd8)$/i;

export function pickBrandAccent(brand) {
  const colors = Array.isArray(brand?.colors) ? brand.colors : [];
  if (colors.length === 0) return '#c2452a';
  const namedAccent = colors.find((c) => ACCENT_NAME_PATTERN.test(c?.name || ''));
  if (namedAccent?.value) return namedAccent.value;
  const nonNeutral = colors.find((c) => c?.value && !NEUTRAL_PATTERN.test(c.value));
  return nonNeutral?.value || colors[0].value || '#c2452a';
}

// The set of installed agent template slugs (validator uses this to check
// agent_run.config.agent_template_slug references). Returns an empty Set if
// the marketplace_items table is not yet populated.
export function loadKnownAgentTemplates(db) {
  try {
    const rows = db.prepare("SELECT slug FROM marketplace_items WHERE kind = 'agent'").all();
    return new Set(rows.map((r) => r.slug));
  } catch {
    return new Set();
  }
}
