import type { Command } from '../commands.js'
import type { LocalCommandCall } from '../types/command.js'
import {
  loadRules,
  deleteRule,
  getTopRules,
} from '../services/behaviorRules/rules.js'

const call: LocalCommandCall = async (args) => {
  const parts = args.trim().split(/\s+/)
  const subcommand = parts[0]?.toLowerCase() ?? ''

  if (!subcommand || subcommand === 'list') {
    const rules = await getTopRules(20)
    if (rules.length === 0) {
      return {
        type: 'text',
        value:
          'No behavioral rules yet. Rules are extracted automatically when you correct or confirm approaches.',
      }
    }

    const lines = ['Behavioral Rules', '']
    for (const rule of rules) {
      const confidence = Math.round(rule.confidence * 100)
      const icon = rule.source === 'correction' ? '🔴' : rule.source === 'confirmation' ? '🟢' : '🔵'
      lines.push(`  ${icon} [${rule.id.slice(0, 6)}] (${confidence}%) ${rule.trigger}`)
      lines.push(`    → ${rule.action}`)
    }
    return { type: 'text', value: lines.join('\n') }
  }

  if (subcommand === 'delete' || subcommand === 'rm') {
    const id = parts[1]
    if (!id) {
      return { type: 'text', value: 'Usage: /rules delete <rule-id>' }
    }
    const deleted = await deleteRule(id)
    return {
      type: 'text',
      value: deleted
        ? `Rule ${id} deleted.`
        : `Rule ${id} not found.`,
    }
  }

  if (subcommand === 'count') {
    const state = await loadRules()
    return {
      type: 'text',
      value: `${state.rules.length} behavioral rules stored.`,
    }
  }

  return {
    type: 'text',
    value: 'Usage: /rules [list|delete <id>|count]',
  }
}

const rules = {
  type: 'local',
  name: 'rules',
  description: 'View or manage learned behavioral rules',
  argumentHint: '[list|delete <id>|count]',
  supportsNonInteractive: true,
  load: () => Promise.resolve({ call }),
} satisfies Command

export default rules
