/**
 * /provider command — manage AI providers
 *
 * /provider list       — show all configured providers
 * /provider add        — add a new custom provider
 * /provider remove <id> — remove a custom provider
 * /provider <id>       — switch to a configured provider
 */
import chalk from 'chalk'
import React from 'react'
import type { CommandResultDisplay, LocalJSXCommandCall, LocalJSXCommandOnDone } from '../../types/command.js'
import {
  getConfiguredProviders,
  switchActiveProvider,
  addCustomProvider,
  removeCustomProvider,
} from '../../utils/providerSetupPrompt.js'
import { getGlobalConfig } from '../../utils/config.js'

export const call: LocalJSXCommandCall = async (onDone, _context, args): Promise<React.ReactNode> => {
  const trimmed = (args || '').trim()
  const [subcommand, ...rest] = trimmed.split(/\s+/)

  if (!subcommand || subcommand === 'list') {
    handleList(onDone)
    return null
  }

  if (subcommand === 'add') {
    handleAdd(rest, onDone)
    return null
  }

  if (subcommand === 'remove' || subcommand === 'rm') {
    const id = rest[0]
    if (!id) {
      onDone('Usage: /provider remove <provider-id>', { display: 'system' })
      return null
    }
    handleRemove(id, onDone)
    return null
  }

  // Try switching to the given provider
  handleSwitch(subcommand, onDone)
  return null
}

type OnDone = LocalJSXCommandOnDone

function handleList(onDone: OnDone): void {
  const configured = getConfiguredProviders()
  const config = getGlobalConfig()

  const lines: string[] = ['']

  if (configured.length === 0) {
    lines.push('  No providers configured. Run /provider add to set one up.')
  } else {
    lines.push(`  ${chalk.bold('Configured Providers')}`)
    lines.push('')
    for (const p of configured) {
      const marker = p.isActive ? chalk.hex('#E5A320')(' ▸ ') : '   '
      const model = p.model ? chalk.dim(` (${p.model})`) : ''
      const activeLabel = p.isActive ? chalk.dim(' — active') : ''
      lines.push(`${marker}${chalk.bold(p.name)}${model}${activeLabel}`)
    }
  }

  // Show custom providers
  const customs = config.customProviders ?? []
  if (customs.length > 0) {
    lines.push('')
    lines.push(`  ${chalk.dim('Custom providers:')}`)
    for (const cp of customs) {
      const isActive = config.provider === cp.id
      const marker = isActive ? chalk.hex('#E5A320')(' ▸ ') : '   '
      lines.push(`${marker}${cp.name} ${chalk.dim(`(${cp.baseUrl})`)}${isActive ? chalk.dim(' — active') : ''}`)
      lines.push(`     ID: ${chalk.cyan(cp.id)} · Model: ${cp.defaultModel}`)
    }
  }

  lines.push('')
  lines.push(`  ${chalk.dim('Commands: /provider add · /provider remove <id> · /provider <id>')}`)
  lines.push('')

  onDone(lines.join('\n'))
}

function handleAdd(args: string[], onDone: OnDone): void {
  // Parse inline arguments: /provider add <name> <baseUrl> <apiKey> <defaultModel>
  if (args.length >= 4) {
    const [name, baseUrl, apiKey, ...modelParts] = args
    const defaultModel = modelParts.join(' ')
    const id = name!.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '')

    addCustomProvider({
      id,
      name: name!,
      baseUrl: baseUrl!,
      apiKey: apiKey!,
      defaultModel,
    })

    onDone(`${chalk.green('✓')} Provider "${name}" added (ID: ${chalk.cyan(id)}). Switch with: /provider ${id}`)
    return
  }

  // Not enough args — show usage
  const lines = [
    '',
    `  ${chalk.bold('Add a Custom Provider')}`,
    '',
    `  ${chalk.dim('Usage:')} /provider add <name> <base-url> <api-key> <default-model>`,
    '',
    `  ${chalk.dim('Examples:')}`,
    `  /provider add OpenRouter https://openrouter.ai/api/v1 sk-or-... anthropic/claude-sonnet-4`,
    `  /provider add Together https://api.together.xyz/v1 tok-... meta-llama/Llama-3-70b`,
    `  /provider add Ollama http://localhost:11434/v1 ollama llama3.1`,
    `  /provider add Groq https://api.groq.com/openai/v1 gsk_... llama-3.3-70b-versatile`,
    '',
  ]
  onDone(lines.join('\n'))
}

function handleRemove(id: string, onDone: OnDone): void {
  const removed = removeCustomProvider(id)
  if (removed) {
    onDone(`${chalk.green('✓')} Provider "${id}" removed.`)
  } else {
    onDone(`Provider "${id}" not found in custom providers. Use /provider list to see available providers.`, { display: 'system' })
  }
}

function handleSwitch(providerId: string, onDone: OnDone): void {
  const configured = getConfiguredProviders()
  const match = configured.find(p => p.id === providerId || p.name.toLowerCase() === providerId.toLowerCase())

  if (!match) {
    onDone(`Provider "${providerId}" not found. Use /provider list to see available providers.`, { display: 'system' })
    return
  }

  switchActiveProvider(match.id)
  onDone(`${chalk.green('✓')} Switched to ${chalk.bold(match.name)}. Restart recommended for full effect.`)
}
