/**
 * `workflow run` — Execute a workflow by name.
 *
 * Resolves the workflow, passes message args, and shows real-time progress.
 * With --detach, runs in background and returns the run ID immediately.
 *
 * @example
 *   workflow run deploy
 *   workflow run deploy --cwd /tmp/project --json
 *   workflow run deploy --detach
 */

import { printJson, type CliOptions } from "../utils.js";

// ---------------------------------------------------------------------------
// Stub: engine integration (not implemented yet)
// ---------------------------------------------------------------------------

interface WorkflowRunResult {
  id: string;
  workflowName: string;
  status: string;
  output?: Record<string, unknown>;
  error?: string;
  startedAt: string;
  completedAt?: string;
}

async function resolveWorkflow(
  _name: string,
  _cwd?: string,
): Promise<unknown> {
  throw new Error('not implemented yet: resolveWorkflow');
}

async function executeWorkflow(
  _workflow: unknown,
  _messageArgs: string[],
  _options: { cwd?: string; detach?: boolean },
): Promise<WorkflowRunResult> {
  throw new Error('not implemented yet: executeWorkflow');
}

// ---------------------------------------------------------------------------
// Command handler
// ---------------------------------------------------------------------------

export async function runCommand(
  args: string[],
  options: CliOptions,
): Promise<void> {
  if (args.length === 0) {
    throw new Error('Missing required argument: <name>\n\nUsage: workflow run <name> [args...] [--cwd <path>] [--detach] [--json]');
  }

  const workflowName = args[0]!;
  const messageArgs = args.slice(1);
  const detach = options.json ? false : false; // --detach is a flag, not in CliOptions yet

  // Parse --detach from raw args (it's a boolean flag).
  // This is handled by the arg parser in the main entry point,
  // but since CliOptions doesn't have detach, we check process.argv.
  const isDetach = process.argv.includes('--detach');

  const workflow = await resolveWorkflow(workflowName, options.cwd);
  const result = await executeWorkflow(workflow, messageArgs, {
    cwd: options.cwd,
    detach: isDetach,
  });

  if (options.json) {
    printJson(result);
    return;
  }

  if (isDetach) {
    console.log(`Workflow started in background.`);
    console.log(`Run ID: ${result.id}`);
    console.log(`Workflow: ${result.workflowName}`);
    console.log(`Status: ${result.status}`);
  } else {
    console.log(`Workflow run completed.`);
    console.log(`  Run ID: ${result.id}`);
    console.log(`  Workflow: ${result.workflowName}`);
    console.log(`  Status: ${result.status}`);
    if (result.output) {
      console.log(`  Output: ${JSON.stringify(result.output)}`);
    }
    if (result.error) {
      console.log(`  Error: ${result.error}`);
    }
  }
}