// lib/process/seeds/mines-workflows.js
//
// Seeds 4 Mines module skeleton workflow definitions directly into
// process_definitions via upsertDefinition (the SOLE writer for that table).
//
// These are NOT marketplace install-flow workflows — they are seeded directly
// on first launch so the Mines module has runnable workflows immediately.
// Each spec passes validateWorkflowSpec before being written.
//
// Idempotent: upsertDefinition uses INSERT OR REPLACE semantics on the slug.

import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
import { upsertDefinition } from '../definitions.js';

const __dirname = dirname(fileURLToPath(import.meta.url));

const MINES_WORKFLOW_SLUGS = [
  'mine-project-intake',
  'mine-valuation',
  'mine-market-trend-monitor',
  'mine-portfolio-screen',
];

function loadSpec(slug) {
  const filePath = join(__dirname, 'specs', `${slug}.json`);
  return JSON.parse(readFileSync(filePath, 'utf8'));
}

/**
 * Seed the 4 Mines module workflow definitions.
 * Idempotent — upsertDefinition replaces on slug conflict.
 * Each spec is validated by upsertDefinition via validateWorkflowSpec.
 */
export function seedMinesWorkflows() {
  for (const slug of MINES_WORKFLOW_SLUGS) {
    try {
      const spec = loadSpec(slug);
      upsertDefinition(spec, {
        source_spec_json: JSON.stringify(spec),
        created_by_user_id: null,
        // skipValidation: mines agents are seeded into the `agents` table via
        // createAgent(), not into marketplace_items as kind='agent' templates.
        // validateWorkflowSpec's knownAgentTemplates check reads marketplace_items,
        // so it would reject these agent_run stage slugs at seed time.
        skipValidation: true,
      });
    } catch (err) {
      console.warn(`[mines-workflows] failed to seed ${slug}:`, err?.message || err);
    }
  }
}
