/**
 * /flowctl Command
 *
 * Controls an active SANDCODE Flow.
 * These are local-only operations that don't need AI involvement.
 *
 * Usage:
 *   /flowctl status      — Show current flow progress
 *   /flowctl stop        — Stop the current flow and save checkpoint
 *   /flowctl checkpoints — List all checkpoints
 *   /flowctl resume      — Resume a paused flow
 *   /flowctl instincts   — Show extracted instincts
 *   /flowctl failures    — Show tracked failure patterns
 */

import type { LocalCommandCall, LocalCommandResult } from '../../types/command.js'
import {
  getActiveFlow,
  getFlowStatus,
  getCheckpointsSummary,
  pauseFlow,
  resumeFlow,
} from '../../services/FlowEngine/FlowEngine.js'
import { getForgeStatus } from '../../services/Forge/ForgeDaemon.js'
import { loadAllInstincts } from '../../services/InstinctEngine/instinctStore.js'
import { getFailureSummary } from '../../services/InstinctEngine/failureTracker.js'

export const call: LocalCommandCall = async (args, _context): Promise<LocalCommandResult> => {
  const trimmedArgs = (args ?? '').trim()

  if (trimmedArgs === 'status' || trimmedArgs === '') {
    return { type: 'text', value: await handleStatus() }
  }

  if (trimmedArgs === 'stop') {
    return { type: 'text', value: await handleStop() }
  }

  if (trimmedArgs === 'checkpoints' || trimmedArgs === 'cps') {
    return { type: 'text', value: await handleCheckpoints() }
  }

  if (trimmedArgs === 'resume') {
    return { type: 'text', value: await handleResume() }
  }

  if (trimmedArgs === 'instincts') {
    return { type: 'text', value: await handleInstincts() }
  }

  if (trimmedArgs === 'failures') {
    return { type: 'text', value: await handleFailures() }
  }

  return {
    type: 'text',
    value: [
      'Unknown flowctl command.',
      '',
      'Available commands:',
      '  /flowctl status      — Show current flow progress',
      '  /flowctl stop        — Stop the current flow',
      '  /flowctl checkpoints — List all checkpoints',
      '  /flowctl resume      — Resume a paused flow',
      '  /flowctl instincts   — Show extracted instincts',
      '  /flowctl failures    — Show tracked failure patterns',
    ].join('\n'),
  }
}

async function handleStatus(): Promise<string> {
  const lines: string[] = []

  lines.push(getFlowStatus())
  lines.push('')

  const forgeStatus = getForgeStatus()
  if (forgeStatus.running) {
    lines.push(`Forge: ${forgeStatus.runsCompleted} runs (${forgeStatus.runsPassed} passed, ${forgeStatus.runsFailed} failed)`)
  } else {
    lines.push('Forge: Not running')
  }

  return lines.join('\n')
}

async function handleStop(): Promise<string> {
  const existing = getActiveFlow()
  if (!existing) {
    return 'No active flow to stop.'
  }

  await pauseFlow()
  return `Flow paused: ${existing.id}\nUse /flowctl resume to continue.`
}

async function handleCheckpoints(): Promise<string> {
  return getCheckpointsSummary()
}

async function handleResume(): Promise<string> {
  const state = await resumeFlow()
  if (!state) {
    return 'No paused flow to resume.'
  }
  return `Flow resumed: ${state.id}\nStatus: ${state.status}`
}

async function handleInstincts(): Promise<string> {
  const instincts = await loadAllInstincts()

  if (instincts.length === 0) {
    return 'No instincts extracted yet. Use /flow to start autonomous development and SANDCODE will learn your patterns.'
  }

  const lines: string[] = [`Extracted Instincts (${instincts.length}):`, '']

  for (const instinct of instincts.sort((a, b) => b.confidence - a.confidence)) {
    const scope = instinct.scope === 'global' ? '[GLOBAL]' : '[LOCAL]'
    lines.push(`  ${scope} ${instinct.name} (${(instinct.confidence * 100).toFixed(0)}% confidence, ${instinct.usageCount}x used)`)
    lines.push(`    Triggers: ${instinct.triggers.join(', ')}`)
    lines.push(`    Steps: ${instinct.steps.length} | Gotchas: ${instinct.gotchas.length}`)
  }

  return lines.join('\n')
}

async function handleFailures(): Promise<string> {
  return getFailureSummary()
}
