/**
 * /flow Command
 *
 * Starts a SANDCODE Flow autonomous development loop.
 *
 * Usage:
 *   /flow <intent>     — Start a new flow with the given intent
 *   /flow status       — Show current flow progress
 *   /flow stop         — Stop the current flow and save checkpoint
 *   /flow checkpoints  — List all checkpoints
 *   /flow resume       — Resume a paused flow
 *   /flow instincts    — Show extracted instincts
 *   /flow failures     — Show tracked failure patterns
 */

import type { LocalCommandCall, LocalCommandResult } from '../../types/command.js'
import {
  startFlow,
  getActiveFlow,
  getFlowStatus,
  getCheckpointsSummary,
  pauseFlow,
  resumeFlow,
} from '../../services/FlowEngine/FlowEngine.js'
import { getForgeStatus, initForge } from '../../services/Forge/ForgeDaemon.js'
import { findMatchingInstincts, 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()

  // Subcommand routing
  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() }
  }

  // Default: start a new flow with the args as intent
  return { type: 'text', value: await handleStartFlow(trimmedArgs) }
}

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

  // Flow status
  lines.push(getFlowStatus())
  lines.push('')

  // Forge status
  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 handleStartFlow(intent: string): Promise<string> {
  const lines: string[] = []

  // Check for existing flow
  const existing = getActiveFlow()
  if (existing) {
    lines.push(`A flow is already active: ${existing.id}`)
    lines.push(`Intent: ${existing.intent}`)
    lines.push(`Status: ${existing.status}`)
    lines.push('Use /flow stop to end it, or /flow status to see progress.')
    return lines.join('\n')
  }

  // Find matching instincts
  const matchingInstincts = await findMatchingInstincts(intent)

  lines.push('SANDCODE Flow Starting...')
  lines.push('')
  lines.push(`Intent: ${intent}`)

  if (matchingInstincts.length > 0) {
    lines.push('')
    lines.push(`Matching instincts (${matchingInstincts.length}):`)
    for (const instinct of matchingInstincts.slice(0, 5)) {
      lines.push(`  - ${instinct.name} (confidence: ${(instinct.confidence * 100).toFixed(0)}%, used ${instinct.usageCount}x)`)
    }
  }

  // Initialize Forge
  try {
    const forgeConfig = await initForge()
    lines.push('')
    lines.push(`Forge initialized: ${forgeConfig.testCommand}`)
  } catch {
    lines.push('')
    lines.push('Forge: Could not auto-detect test command. You may need to configure manually.')
  }

  // Start the flow
  const state = await startFlow(intent)
  lines.push('')
  lines.push(`Flow created: ${state.id}`)
  lines.push('')
  lines.push('Next steps:')
  lines.push('1. The AI will generate a spec for your review')
  lines.push('2. Approve or modify the spec')
  lines.push('3. Flow will plan and execute with verification')

  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 /flow 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()
}
