#!/usr/bin/env node
import assert from 'assert';
import fs from 'fs';
import os from 'os';
import path from 'path';
import { ensureProjectProfile } from './src/server/helpers.js';

function makeTempProject() {
  const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'vlcode-workflow-sync-'));
  fs.mkdirSync(path.join(dir, '.vl-code', 'workflows'), { recursive: true });
  fs.mkdirSync(path.join(dir, 'Apps'), { recursive: true });
  fs.writeFileSync(path.join(dir, 'Apps', 'Demo.vx'), '// VL_VERSION:3.5\n');
  return dir;
}

function main() {
  const seedWorkflowDir = path.join(process.cwd(), 'public', 'seed-workflows');
  const projectDir = makeTempProject();
  const staleWorkflow = {
    version: '3.16',
    name: 'AddPage',
    registry: {
      vars: ['$updatedMeta(OBJECT)', '$newSection(OBJECT)'],
      docs: {
        '1': 'VL 3.5 Syntax Rules',
        '80': 'Agent-800-Section: Section business logic + UI',
        '90': 'Agent-900-App: App entry + routing',
      },
    },
    steps: [
      {
        id: 'LLM_050_UpdateApp',
        in: { docs: ['1', '90'] },
        out: {},
      },
    ],
  };

  const targetPath = path.join(projectDir, '.vl-code', 'workflows', 'add-page.json');
  fs.writeFileSync(targetPath, JSON.stringify(staleWorkflow, null, 2), 'utf-8');

  ensureProjectProfile(projectDir, seedWorkflowDir);

  const refreshedWorkflow = JSON.parse(fs.readFileSync(targetPath, 'utf-8'));
  const updateAppStep = refreshedWorkflow.steps.find((step) => step.id === 'LLM_050_UpdateApp');

  assert(
    refreshedWorkflow.registry.vars.some((entry) => String(entry).includes('$targetAppFilePath')),
    'should refresh stale add-page workflow with targetAppFilePath support'
  );
  assert(
    updateAppStep?.in?.readFiles?.length > 0,
    'should refresh stale add-page workflow with app readFiles input'
  );
  assert(
    updateAppStep?.out && Object.keys(updateAppStep.out).length > 0,
    'should refresh stale add-page workflow with app output mapping'
  );

  fs.rmSync(projectDir, { recursive: true, force: true });
  console.log('\n── Workflow Seed Sync ──');
  console.log('PASS test-workflow-seed-sync.js');
}

main();
