// lib/process/seeds/marketplace-workflows.js
//
// Seeds 3 starter workflow templates as marketplace items (kind='workflow').
// Not installed by default — install flow calls upsertDefinition() (same path
// as the JSON editor and the create_workflow_definition tool). Idempotent.
//
// Specs live on disk as JSON under ./specs/ (mirrors adgm-entity-setup.js).
// Each card stores its full source_spec inside manifest_json.source_spec_json
// so the marketplace install flow can rehydrate it without re-reading disk.
//
// Agent templates referenced (vendor-risk-reviewer, contract-reviewer,
// support-triage-agent) are seeded in lib/process/seeds/agent-templates.js.

import { nowIso } from '../../db.js';
import vendorOnboardingSpec from './specs/vendor-onboarding.json' with { type: 'json' };
import contractReviewSpec from './specs/contract-review.json' with { type: 'json' };
import supportEscalationSpec from './specs/support-escalation.json' with { type: 'json' };

const WORKFLOW_SPECS = {
  'vendor-onboarding': vendorOnboardingSpec,
  'contract-review': contractReviewSpec,
  'support-escalation': supportEscalationSpec,
};

const WORKFLOW_METADATA = [
  { slug: 'vendor-onboarding', title: 'Vendor Onboarding', category: 'procurement', tags: ['workflow', 'procurement', 'starter'],
    risk_summary: 'Intake → automated risk review → buyer sign-off → onboarding pack. All write actions are gated by human_approval.' },
  { slug: 'contract-review', title: 'Contract Review', category: 'legal', tags: ['workflow', 'legal', 'starter'],
    risk_summary: 'Intake → automated clause review → counsel approval (high-risk gate) → review report. Drafts only; no signature step.' },
  { slug: 'support-escalation', title: 'Support Escalation', category: 'support', tags: ['workflow', 'support', 'starter'],
    risk_summary: 'Intake → automated triage → supervisor sign-off → resolution pack. Customer-visible copy never sent without human approval.' },
];

export const MARKETPLACE_WORKFLOW_SEEDS = WORKFLOW_METADATA.map((meta) => {
  const spec = WORKFLOW_SPECS[meta.slug];
  return { ...meta, description: spec.description, author: 'madarx', source_kind: 'builtin', source_url: null, version: '1.0', spec };
});

export const MARKETPLACE_WORKFLOW_SLUGS = MARKETPLACE_WORKFLOW_SEEDS.map((seed) => seed.slug);

function upsertWorkflowItem(db, seed) {
  const id = `workflow:${seed.slug}`;
  const manifestJson = JSON.stringify({ summary: seed.description, source_spec_json: seed.spec });
  const tagsJson = JSON.stringify(seed.tags || []);
  const existing = db.prepare("SELECT id FROM marketplace_items WHERE kind='workflow' AND slug=?").get(seed.slug);
  const args = [seed.title, seed.description, seed.category, seed.author, seed.source_kind, seed.source_url, seed.version, manifestJson, seed.risk_summary, tagsJson];

  if (existing) {
    db.prepare(`UPDATE marketplace_items SET title=?, description=?, category=?, author=?, source_kind=?, source_url=?, version=?, manifest_json=?, risk_summary=?, tags=? WHERE id=?`)
      .run(...args, id);
    return;
  }
  db.prepare(`INSERT INTO marketplace_items (id, kind, slug, title, description, category, author, source_kind, source_url, version, manifest_json, risk_summary, tags, created_at) VALUES (?, 'workflow', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
    .run(id, seed.slug, ...args, nowIso());
  db.prepare(`INSERT OR IGNORE INTO marketplace_installations (item_id, installed) VALUES (?, 0)`).run(id);
}

export function seedMarketplaceWorkflows(db) {
  try {
    for (const seed of MARKETPLACE_WORKFLOW_SEEDS) upsertWorkflowItem(db, seed);
  } catch (err) {
    console.warn('[marketplace-workflows] seed failed:', err?.message || err);
  }
}
