import { randomUUID } from 'node:crypto'
import {
  CURRENT_PROVIDER_PROFILE_ID,
  DEFAULT_PROVIDER_ROUTE_DIAGNOSTIC_MODELS,
  activateCurrentProviderProfile,
  activateProviderProfile,
  areProviderProfilesEquivalent,
  attemptAutoRepairProviderProfile,
  clearActiveProviderConfiguration,
  findProviderProfiles,
  getActiveProviderProfileId,
  getCredentialLabel,
  getCurrentProviderProfile,
  getProviderExperienceDescription,
  getProviderExperienceLabel,
  getProviderProfiles,
  getProviderRoutingStrategyDescription,
  getProviderRoutingStrategyLabel,
  getProviderSourceDescription,
  getProviderSourceLabel,
  getResolvedCurrentProviderProfile,
  getSavedActiveProviderProfile,
  importCompatibleExternalProviderProfiles,
  inspectProviderModelRoutes,
  maskCredential,
  mergeSelectableProviderProfiles,
  saveProviderProfile,
  syncOnboardingState,
  validateProviderProfile,
} from './provider-setup.js'

function loadProviderState() {
  const activeSavedProfile = getSavedActiveProviderProfile()
  const currentEnvProfile = getCurrentProviderProfile()

  return {
    profiles: getProviderProfiles(),
    activeProfileId: getActiveProviderProfileId(),
    activeSavedProfile,
    currentEnvProfile,
    currentProfile:
      activeSavedProfile ?? currentEnvProfile ?? getResolvedCurrentProviderProfile(),
  }
}

function getRoutingDisplayValue(value, fallback) {
  const trimmed = String(value || '').trim()
  return trimmed || fallback
}

function getProviderModelSlotDefaults(routing) {
  const primaryModel = String(routing?.primaryModel || '').trim()
  const executionModel =
    String(routing?.subagentModel || '').trim() || primaryModel
  const fastModel =
    String(routing?.smallFastModel || '').trim() || executionModel || primaryModel
  const planModel = String(routing?.planModel || '').trim() || primaryModel
  const generalModel =
    String(routing?.generalModel || '').trim() || executionModel || primaryModel

  return {
    opusModel: planModel || primaryModel,
    sonnetModel: generalModel || executionModel || primaryModel,
    haikuModel: fastModel || generalModel || executionModel || primaryModel,
  }
}

function getProviderSlotValues(profile) {
  const slotDefaults = getProviderModelSlotDefaults(profile.modelRouting || {})
  return {
    primaryModel: String(profile.modelRouting?.primaryModel || '').trim(),
    haikuModel: slotDefaults.haikuModel,
    sonnetModel: slotDefaults.sonnetModel,
    opusModel: slotDefaults.opusModel,
  }
}

function formatProviderListDescription(profile) {
  const slots = getProviderSlotValues(profile)
  return [
    getProviderSourceLabel(profile),
    getProviderExperienceLabel(profile),
    getProviderRoutingStrategyLabel(profile),
    profile.baseUrl,
    `${getCredentialLabel(profile.authType)} ${maskCredential(profile.credential)}`,
    `Primary ${getRoutingDisplayValue(slots.primaryModel, 'provider default')}`,
    `Sonnet ${getRoutingDisplayValue(slots.sonnetModel, 'provider default')}`,
  ].join(' · ')
}

function formatProviderSummary(profile) {
  const slots = getProviderSlotValues(profile)
  return [
    `Profile: ${profile.name}`,
    `Source: ${getProviderSourceLabel(profile)}`,
    `Source detail: ${getProviderSourceDescription(profile)}`,
    `Route family: ${getProviderExperienceLabel(profile)}`,
    `Path: ${getProviderExperienceDescription(profile)}`,
    `Routing strategy: ${getProviderRoutingStrategyLabel(profile)}`,
    `Strategy note: ${getProviderRoutingStrategyDescription(profile)}`,
    `API URL: ${profile.baseUrl}`,
    `${getCredentialLabel(profile.authType)}: ${maskCredential(profile.credential)}`,
    `Primary model: ${getRoutingDisplayValue(slots.primaryModel, 'provider default')}`,
    `Haiku model: ${getRoutingDisplayValue(slots.haikuModel, 'provider default')}`,
    `Sonnet model: ${getRoutingDisplayValue(slots.sonnetModel, 'provider default')}`,
    `Opus model: ${getRoutingDisplayValue(slots.opusModel, 'provider default')}`,
  ].join('\n')
}

function buildProviderStateOverview(state) {
  const lines = ['Provider control center:']

  if (state.activeSavedProfile) {
    lines.push(`- Active saved profile: ${state.activeSavedProfile.name}`)
  } else {
    lines.push('- Active saved profile: none')
  }

  if (state.currentEnvProfile) {
    lines.push(`- Current API config: ${state.currentEnvProfile.name}`)
  } else {
    lines.push('- Current API config: none')
  }

  if (state.currentProfile) {
    lines.push(`- Current family: ${getProviderExperienceLabel(state.currentProfile)}`)
    lines.push(
      `- Routing strategy: ${getProviderRoutingStrategyLabel(state.currentProfile)}`,
    )
  } else {
    lines.push('- Current family: unavailable')
    lines.push('- Routing strategy: unavailable')
  }

  if (state.activeSavedProfile && state.currentEnvProfile) {
    lines.push(
      areProviderProfilesEquivalent(
        state.activeSavedProfile,
        state.currentEnvProfile,
      )
        ? '- Live env mirrors the active saved profile.'
        : '- Live env differs from the active saved profile. Review current config before switching.',
    )
  }

  return lines
}

function buildValidationGuidance(profile, validation, routeMatrix) {
  const gpt54Route = routeMatrix.find(route => route.model === 'gpt-5.4')
  const codexRoute = routeMatrix.find(route => route.model === 'gpt-5.3-codex')

  if (gpt54Route?.status === 'recommended') {
    const guidance = [
      'Guidance:',
      '- This provider is currently best routed as gpt-5.4 across the primary, Sonnet, and Haiku slots.',
    ]

    if (gpt54Route.effortLevels.includes('max')) {
      guidance.push(
        '- Use `/effort low|medium|high|max` with gpt-5.4 here. `max` is mapped to Responses `reasoning.effort = xhigh` on this validated route.',
      )
    }

    if (codexRoute?.status === 'avoid') {
      guidance.push(
        '- Do not route the Sonnet slot to gpt-5.3-codex on this provider until `/provider validate` shows it as SUPPORTED.',
      )
    }

    if (validation.status === 'ok') {
      return guidance
    }
  }

  if (validation.status === 'ok') {
    return []
  }

  if (
    profile.modelRouting.primaryModel.trim() === 'gpt-5.4' &&
    Array.isArray(validation.details) &&
    validation.details.some(
      detail =>
        detail &&
        detail.status !== 'ok' &&
        Array.isArray(detail.roles) &&
        detail.roles.some(role => role !== 'primary'),
    )
  ) {
    return [
      'Guidance:',
      '- This gateway is currently verified for native Clavue workflows on gpt-5.4.',
      '- One or more non-primary slots are degraded here. Run `clavue provider` and choose reconfigure to switch the full slot routing back to gpt-5.4.',
    ]
  }

  if (validation.status === 'warn') {
    return [
      'Guidance:',
      '- The provider can answer chat requests, but some native workflows may still degrade on the current routing.',
      '- Run `clavue provider` to adjust the active profile and model slots, then rerun `clavue provider validate`.',
    ]
  }

  return []
}

function getDefaultSetupHintLine(commandPrefix) {
  if (commandPrefix === 'clavue provider') {
    return 'Run `clavue provider` with no arguments to open the full provider setup flow.'
  }

  return 'Use `clavue provider` outside the session to open the full /provider setup flow.'
}

function parseSaveCurrentArgs(rawArgs) {
  const trimmedArgs = String(rawArgs || '').trim()
  if (!trimmedArgs) {
    return {
      hasExplicitName: false,
    }
  }

  return {
    hasExplicitName: true,
    name: trimmedArgs,
  }
}

function findSavedProviderByExactName(name) {
  const normalizedName = String(name || '').trim().toLowerCase()
  if (!normalizedName) {
    return null
  }

  return (
    getProviderProfiles().find(
      profile => String(profile.name || '').trim().toLowerCase() === normalizedName,
    ) || null
  )
}

function findEquivalentSavedProvider(profile) {
  return (
    getProviderProfiles().find(savedProfile =>
      areProviderProfilesEquivalent(savedProfile, profile),
    ) || null
  )
}

function createSavableCurrentProfile(currentProfile, name) {
  const timestamp = Date.now()

  return {
    ...currentProfile,
    id: randomUUID(),
    name: String(name || '').trim() || currentProfile.name,
    createdAt: timestamp,
    updatedAt: timestamp,
  }
}

function buildHelpText(commandPrefix = '/provider') {
  return [
    `Usage: ${commandPrefix} [list|current|doctor|clear|save-current [name]|adopt-current [name]|validate [profile]|probe [profile]|matrix [profile]|repair [profile]|import [--from zcf|ccjk]|use <profile>|activate <profile>|<profile>]`,
    '',
    'Manage saved provider profiles and model slots for Clavue.',
    getDefaultSetupHintLine(commandPrefix),
    '',
    'Examples:',
    `  ${commandPrefix} list`,
    `  ${commandPrefix} current`,
    `  ${commandPrefix} doctor`,
    `  ${commandPrefix} validate`,
    `  ${commandPrefix} probe`,
    `  ${commandPrefix} matrix`,
    `  ${commandPrefix} repair`,
    `  ${commandPrefix} import --from zcf`,
    `  ${commandPrefix} save-current kimi-main`,
    `  ${commandPrefix} activate kimi`,
    `  ${commandPrefix} use current`,
  ].join('\n')
}

function formatMatchList(matches) {
  return matches.map(profile => `- ${profile.name} (${profile.baseUrl})`).join('\n')
}

function resolveSingleProviderMatch(profileQuery, commandPrefix = '/provider') {
  const matches = findProviderProfiles(profileQuery)

  if (matches.length === 0) {
    return {
      error: `No saved profile matched '${profileQuery}'. Run ${commandPrefix} list to inspect saved names.`,
    }
  }

  if (matches.length > 1) {
    return {
      error: `Multiple profiles matched '${profileQuery}'. Be more specific:\n${formatMatchList(
        matches,
      )}`,
    }
  }

  return { profile: matches[0] }
}

function syncLiveSession(context, profile) {
  if (typeof context?.onChangeAPIKey === 'function') {
    context.onChangeAPIKey()
  }

  if (typeof context?.setAppState === 'function') {
    const mainLoopModel =
      String(profile?.modelRouting?.primaryModel || '').trim() || null
    context.setAppState(prev => ({
      ...prev,
      mainLoopModel,
      mainLoopModelForSession: null,
      authVersion: (prev.authVersion || 0) + 1,
    }))
  }
}

async function formatRouteMatrix(profile, commandPrefix = '/provider') {
  const routes = await inspectProviderModelRoutes(
    profile,
    DEFAULT_PROVIDER_ROUTE_DIAGNOSTIC_MODELS,
  )
  const guidance = buildValidationGuidanceWithCommands(
    profile,
    { status: 'ok', lines: [] },
    routes,
    commandPrefix,
  )

  return [
    `GPT-5.x route matrix for ${profile.name}:`,
    ...routes.map(route => route.line),
    ...(guidance.length > 0 ? ['', ...guidance] : []),
  ].join('\n')
}

function parseImportSource(rawArgs) {
  const trimmedArgs = String(rawArgs || '').trim()
  if (!trimmedArgs) {
    return {}
  }

  const sourceMatch = trimmedArgs.match(/^(?:--from(?:=|\s+))?([a-z0-9_-]+)$/i)
  if (!sourceMatch) {
    return {
      error:
        "Invalid import arguments. Use `import --from zcf`, `import --from ccjk`, or plain `import`.",
    }
  }

  const requestedSource = sourceMatch[1].trim().toLowerCase()
  if (!requestedSource || requestedSource === 'all') {
    return {}
  }

  if (requestedSource === 'zcf' || requestedSource === 'ccjk') {
    return {
      sourceId: requestedSource,
    }
  }

  return {
    error: `Unsupported import source '${requestedSource}'. Supported sources: zcf, ccjk.`,
  }
}

function formatCompatibleImportProfile(profile) {
  return `- ${profile.name} · ${profile.baseUrl} · ${getProviderExperienceLabel(
    profile,
  )} · ${getProviderRoutingStrategyLabel(profile)}`
}

function buildCompatibleImportMessage(result, commandPrefix) {
  const sourceLabel =
    result.sourceId === 'all' ? 'compatible sources' : result.sourceId

  if (result.discoveredProfiles.length === 0 && !result.activeProfileId) {
    return `No compatible provider profiles were found in ${sourceLabel}.`
  }

  const lines = [
    `Compatibility import from ${sourceLabel}:`,
    `Discovered profiles: ${result.discoveredProfiles.length}`,
    `Imported profiles: ${result.importedProfiles.length}`,
    `Already available: ${result.skippedProfiles.length}`,
  ]

  if (result.importedProfiles.length > 0) {
    lines.push('', 'Imported profiles:')
    lines.push(...result.importedProfiles.map(profile => formatCompatibleImportProfile(profile)))
  }

  if (result.skippedProfiles.length > 0) {
    lines.push('', 'Already available:')
    lines.push(...result.skippedProfiles.map(profile => formatCompatibleImportProfile(profile)))
  }

  if (result.activeProfileId) {
    lines.push('', `Source active profile: ${result.activeProfileId}`)
    if (result.syncedActiveProfile) {
      lines.push(`Synced active profile: ${result.syncedActiveProfile.name}`)
    } else {
      lines.push(
        'Active sync: skipped because a different local profile or live env is already pinned.',
      )
    }
  }

  lines.push('', `Next step: run \`${commandPrefix} matrix\` or \`${commandPrefix} validate\`.`)

  return lines.join('\n')
}

function buildValidationGuidanceWithCommands(profile, validation, routeMatrix, commandPrefix) {
  const guidance = buildValidationGuidance(profile, validation, routeMatrix)
  if (guidance.length === 0) {
    return guidance
  }

  return guidance.map(line =>
    line
      .replace(/`\/provider validate`/g, `\`${commandPrefix} validate\``)
      .replace(new RegExp('`my' + 'claude provider`', 'g'), '`clavue provider`'),
  )
}

function formatDoctorIssue(status, text) {
  return `- ${status.toUpperCase()}: ${text}`
}

function getProviderDoctorVerdict(validation, hasCurrentProfile) {
  if (!hasCurrentProfile) {
    return 'blocked'
  }

  if (!validation || validation.status === 'error') {
    return 'repair required'
  }

  if (validation.status === 'warn') {
    return 'usable with warnings'
  }

  return 'ready'
}

function buildProviderDoctorReport(input) {
  const {
    activeSavedProfile,
    commandPrefix,
    currentEnvProfile,
    currentProfile,
    profiles,
    routeMatrix,
    setupCommand,
    validation,
  } = input
  const verdict = getProviderDoctorVerdict(validation, currentProfile !== null)
  const lines = [
    'Provider doctor:',
    `Verdict: ${verdict}`,
    '',
    'Source of truth:',
    '- Config namespace: .clavue',
    `- Saved profiles: ${profiles.length}`,
    activeSavedProfile
      ? `- Active saved profile: ${activeSavedProfile.name}`
      : '- Active saved profile: None',
    currentEnvProfile
      ? `- Current API config: ${currentEnvProfile.name}`
      : '- Current API config: None',
  ]

  if (activeSavedProfile && currentEnvProfile) {
    lines.push(
      areProviderProfilesEquivalent(activeSavedProfile, currentEnvProfile)
        ? '- Drift check: live env mirrors the active saved profile.'
        : '- Drift check: live env differs from the active saved profile.',
    )
  } else if (currentEnvProfile && !activeSavedProfile) {
    lines.push(
      `- Drift check: live env is not saved yet. Run \`${commandPrefix} save-current <name>\` if this route should persist.`,
    )
  } else if (activeSavedProfile && !currentEnvProfile) {
    lines.push('- Drift check: using the active saved profile with no live env override.')
  } else {
    lines.push('- Drift check: no provider route is currently available.')
  }

  lines.push('', 'Active route:')
  if (currentProfile) {
    lines.push(...formatProviderSummary(currentProfile).split('\n'))
  } else {
    lines.push('No active provider route is available.')
  }

  lines.push('', 'Validation:')
  if (validation) {
    lines.push(`- Status: ${validation.status}`)
    lines.push(
      ...validation.lines.map(line =>
        formatDoctorIssue(
          line.includes('[ERROR]') ? 'error' : line.includes('[WARN]') ? 'warn' : 'ok',
          line,
        ),
      ),
    )
  } else {
    lines.push('- Status: blocked')
    lines.push(
      formatDoctorIssue(
        'error',
        `No active route. Run \`${setupCommand}\` to create or activate a provider profile.`,
      ),
    )
  }

  lines.push('', 'GPT-5.x route matrix:')
  if (routeMatrix.length > 0) {
    lines.push(...routeMatrix.map(route => route.line))
  } else {
    lines.push('- No route matrix is available without an active provider route.')
  }

  if (currentProfile && validation) {
    const guidance = buildValidationGuidanceWithCommands(
      currentProfile,
      validation,
      routeMatrix,
      commandPrefix,
    )
    if (guidance.length > 0) {
      lines.push('', ...guidance)
    }
  }

  lines.push('', 'Next actions:')
  if (!currentProfile) {
    lines.push(`- Run \`${setupCommand}\` to configure a provider profile.`)
    lines.push(`- Run \`${commandPrefix} import --from zcf\` if you already use zcf.`)
  } else if (!activeSavedProfile && currentEnvProfile) {
    lines.push(`- Run \`${commandPrefix} save-current <name>\` to persist this live route.`)
    lines.push(`- Run \`${commandPrefix} validate\` after saving or editing.`)
  } else if (validation?.status === 'error' || validation?.status === 'warn') {
    lines.push(`- Run \`${commandPrefix} repair\` for the safest automatic routing repair.`)
    lines.push(`- Run \`${commandPrefix} validate\` after repair.`)
  } else {
    lines.push(`- No immediate repair needed. Run \`${commandPrefix} matrix\` for deeper route detail.`)
  }

  return lines.join('\n')
}

async function formatCapabilityProbe(profile, commandPrefix) {
  const validation = await validateProviderProfile(profile)
  const routeMatrix = await inspectProviderModelRoutes(
    profile,
    DEFAULT_PROVIDER_ROUTE_DIAGNOSTIC_MODELS,
  )
  const slots = getProviderSlotValues(profile)

  return [
    `Capability probe for ${profile.name}:`,
    `Route family: ${getProviderExperienceLabel(profile)}`,
    `Routing strategy: ${getProviderRoutingStrategyLabel(profile)}`,
    `Configured primary: ${getRoutingDisplayValue(slots.primaryModel, 'provider default')}`,
    `Configured Haiku: ${getRoutingDisplayValue(slots.haikuModel, 'provider default')}`,
    `Configured Sonnet: ${getRoutingDisplayValue(slots.sonnetModel, 'provider default')}`,
    `Configured Opus: ${getRoutingDisplayValue(slots.opusModel, 'provider default')}`,
    '',
    'Configured route validation:',
    ...validation.lines,
    `Status: ${validation.status}`,
    '',
    'GPT-5.x route matrix:',
    ...routeMatrix.map(route => route.line),
    '',
    'Route detail:',
    ...routeMatrix.map(route => {
      const effortLevels =
        route.effortLevels.length > 0 ? route.effortLevels.join(', ') : 'none'
      return `- ${route.model}: transport=${route.transport}; policy=${route.policyTransport}; workflow=${route.workflowMode}; quality=${route.qualityTier}; effort=${effortLevels}`
    }),
    ...buildValidationGuidanceWithCommands(
      profile,
      validation,
      routeMatrix,
      commandPrefix,
    ),
  ].join('\n')
}

export async function call(args, context) {
  const trimmedArgs = String(args || '').trim()
  const commandPrefix =
    typeof context?.commandPrefix === 'string' &&
    String(context.commandPrefix).trim()
      ? String(context.commandPrefix).trim()
      : '/provider'

  if (
    !trimmedArgs ||
    trimmedArgs === 'help' ||
    trimmedArgs === '--help' ||
    trimmedArgs === '-h'
  ) {
    return {
      type: 'text',
      value: buildHelpText(commandPrefix),
    }
  }

  if (trimmedArgs === 'list') {
    const state = loadProviderState()
    if (state.profiles.length === 0 && !state.currentProfile) {
      return {
        type: 'text',
        value:
          commandPrefix === 'clavue provider'
            ? 'No provider profiles are configured yet. Run `clavue provider` with no arguments to create one.'
            : 'No provider profiles are configured yet. Run `clavue provider` outside the session to create one.',
      }
    }

    const sections = [
      buildHelpText(commandPrefix),
      buildProviderStateOverview(state).join('\n'),
    ]

    if (state.profiles.length > 0) {
      sections.push(
        [
          'Saved provider profiles:',
          ...state.profiles.map(profile => {
            const suffix =
              state.activeProfileId === profile.id ? ' (active)' : ''
            return `- ${profile.name}${suffix} · ${formatProviderListDescription(profile)}`
          }),
        ].join('\n'),
      )
    }

    if (state.currentEnvProfile) {
      sections.push(
        ['Current API config:', formatProviderSummary(state.currentEnvProfile)].join(
          '\n',
        ),
      )
    }

    if (state.activeSavedProfile) {
      sections.push(
        ['Active saved profile:', formatProviderSummary(state.activeSavedProfile)].join(
          '\n',
        ),
      )
    }

    return {
      type: 'text',
      value: sections.join('\n\n'),
    }
  }

  if (trimmedArgs === 'current') {
    const state = loadProviderState()

    if (!state.currentProfile && !state.activeSavedProfile && !state.currentEnvProfile) {
      return {
        type: 'text',
        value: 'No active provider profile is set.',
      }
    }

    const sections = [buildProviderStateOverview(state).join('\n')]

    if (state.activeSavedProfile) {
      sections.push(`Active saved profile:\n${formatProviderSummary(state.activeSavedProfile)}`)
    }

    if (state.currentEnvProfile) {
      sections.push(`Current API config:\n${formatProviderSummary(state.currentEnvProfile)}`)
    }

    return {
      type: 'text',
      value: sections.join('\n\n'),
    }
  }

  if (trimmedArgs === 'doctor' || trimmedArgs === 'check') {
    const state = loadProviderState()
    const validation = state.currentProfile
      ? await validateProviderProfile(state.currentProfile)
      : null
    const routeMatrix = state.currentProfile
      ? await inspectProviderModelRoutes(
          state.currentProfile,
          DEFAULT_PROVIDER_ROUTE_DIAGNOSTIC_MODELS,
        )
      : []

    return {
      type: 'text',
      value: buildProviderDoctorReport({
        activeSavedProfile: state.activeSavedProfile,
        commandPrefix,
        currentEnvProfile: state.currentEnvProfile,
        currentProfile: state.currentProfile,
        profiles: state.profiles,
        routeMatrix,
        setupCommand: 'clavue provider',
        validation,
      }),
    }
  }

  if (trimmedArgs === 'clear') {
    clearActiveProviderConfiguration()
    syncLiveSession(context, null)
    return {
      type: 'text',
      value: 'Cleared the active provider profile configuration.',
    }
  }

  const saveCurrentMatch = trimmedArgs.match(
    /^(save-current|adopt-current)(?:\s+(.+))?$/i,
  )
  if (saveCurrentMatch) {
    const currentProfile = getCurrentProviderProfile()
    if (!currentProfile) {
      return {
        type: 'text',
        value:
          'No live current API configuration is available to save. Configure a provider credential first or reopen `clavue provider`.',
      }
    }

    const parsedArgs = parseSaveCurrentArgs(saveCurrentMatch[2] || '')
    const targetName = parsedArgs.name?.trim() || currentProfile.name
    const existingNamedProfile = findSavedProviderByExactName(targetName)

    if (existingNamedProfile) {
      if (areProviderProfilesEquivalent(existingNamedProfile, currentProfile)) {
        const activatedProfile =
          activateProviderProfile(existingNamedProfile.id) || existingNamedProfile
        syncOnboardingState()
        syncLiveSession(context, activatedProfile)
        return {
          type: 'text',
          value: [
            `Current API config already matches saved profile ${activatedProfile.name}.`,
            'Activated the existing saved profile instead of overwriting it.',
            formatProviderSummary(activatedProfile),
          ].join('\n'),
        }
      }

      return {
        type: 'text',
        value: [
          `Cannot save the current API config as '${targetName}' because that saved profile already exists with different settings.`,
          `Choose a different name or reopen \`${commandPrefix}\` to compare and update the profile explicitly.`,
        ].join('\n'),
      }
    }

    if (!parsedArgs.hasExplicitName) {
      const equivalentProfile = findEquivalentSavedProvider(currentProfile)
      if (equivalentProfile) {
        const activatedProfile =
          activateProviderProfile(equivalentProfile.id) || equivalentProfile
        syncOnboardingState()
        syncLiveSession(context, activatedProfile)
        return {
          type: 'text',
          value: [
            `Current API config already matches saved profile ${activatedProfile.name}.`,
            'Activated the existing saved profile instead of creating a duplicate.',
            formatProviderSummary(activatedProfile),
          ].join('\n'),
        }
      }
    }

    const savedProfile = saveProviderProfile(
      createSavableCurrentProfile(currentProfile, targetName),
      {
        activate: true,
      },
    )
    syncOnboardingState()
    syncLiveSession(context, savedProfile)
    return {
      type: 'text',
      value: [
        `Saved current API config as profile ${savedProfile.name} and activated it.`,
        formatProviderSummary(savedProfile),
      ].join('\n'),
    }
  }

  const importMatch = trimmedArgs.match(/^import(?:\s+(.+))?$/i)
  if (importMatch) {
    const parsedSource = parseImportSource(importMatch[1] || '')
    if ('error' in parsedSource) {
      return {
        type: 'text',
        value: parsedSource.error,
      }
    }

    const importResult = importCompatibleExternalProviderProfiles({
      sourceId: parsedSource.sourceId,
    })

    if (importResult.syncedActiveProfile) {
      syncLiveSession(context, importResult.syncedActiveProfile)
    }

    return {
      type: 'text',
      value: buildCompatibleImportMessage(importResult, commandPrefix),
    }
  }

  const matrixMatch = trimmedArgs.match(/^matrix(?:\s+(.+))?$/i)
  if (matrixMatch) {
    const profileQuery = matrixMatch[1]?.trim()
    let profile = null

    if (profileQuery) {
      const matched = resolveSingleProviderMatch(profileQuery, commandPrefix)
      if ('error' in matched) {
        return {
          type: 'text',
          value: matched.error,
        }
      }
      profile = matched.profile
    } else {
      profile = getResolvedCurrentProviderProfile()
    }

    if (!profile) {
      return {
        type: 'text',
        value: 'No active provider profile is set.',
      }
    }

    return {
      type: 'text',
      value: await formatRouteMatrix(profile, commandPrefix),
    }
  }

  const probeMatch = trimmedArgs.match(/^probe(?:\s+(.+))?$/i)
  if (probeMatch) {
    const profileQuery = probeMatch[1]?.trim()
    let profile = null

    if (profileQuery) {
      const matched = resolveSingleProviderMatch(profileQuery, commandPrefix)
      if ('error' in matched) {
        return {
          type: 'text',
          value: matched.error,
        }
      }
      profile = matched.profile
    } else {
      profile = getResolvedCurrentProviderProfile()
    }

    if (!profile) {
      return {
        type: 'text',
        value: 'No active provider profile is set.',
      }
    }

    return {
      type: 'text',
      value: await formatCapabilityProbe(profile, commandPrefix),
    }
  }

  const validateMatch = trimmedArgs.match(/^(validate|test)(?:\s+(.+))?$/i)
  if (validateMatch) {
    const profileQuery = validateMatch[2]?.trim()
    let profile = null

    if (profileQuery) {
      const matched = resolveSingleProviderMatch(profileQuery, commandPrefix)
      if ('error' in matched) {
        return {
          type: 'text',
          value: matched.error,
        }
      }
      profile = matched.profile
    } else {
      profile = getResolvedCurrentProviderProfile()
    }

    if (!profile) {
      return {
        type: 'text',
        value: 'No active provider profile is set.',
      }
    }

    const validation = await validateProviderProfile(profile)
    const routeMatrix = await inspectProviderModelRoutes(
      profile,
      DEFAULT_PROVIDER_ROUTE_DIAGNOSTIC_MODELS,
    )
    return {
      type: 'text',
      value: [
        `Validation for ${profile.name}:`,
        ...validation.lines,
        `Status: ${validation.status}`,
        '',
        'GPT-5.x route matrix:',
        ...routeMatrix.map(route => route.line),
        ...buildValidationGuidanceWithCommands(
          profile,
          validation,
          routeMatrix,
          commandPrefix,
        ),
      ].join('\n'),
    }
  }

  const repairMatch = trimmedArgs.match(/^repair(?:\s+(.+))?$/i)
  if (repairMatch) {
    const profileQuery = repairMatch[1]?.trim()
    let profile = null

    if (profileQuery) {
      const matched = resolveSingleProviderMatch(profileQuery, commandPrefix)
      if ('error' in matched) {
        return {
          type: 'text',
          value: matched.error,
        }
      }
      profile = matched.profile
    } else {
      profile = getResolvedCurrentProviderProfile()
    }

    if (!profile) {
      return {
        type: 'text',
        value: 'No active provider profile is set.',
      }
    }

    const repairResult = await attemptAutoRepairProviderProfile(profile)
    if (repairResult.repaired && repairResult.profile) {
      syncLiveSession(context, repairResult.profile)
      const originalFamily = getProviderExperienceLabel(profile)
      const repairedFamily = getProviderExperienceLabel(repairResult.profile)
      const originalStrategy = getProviderRoutingStrategyLabel(profile)
      const repairedStrategy = getProviderRoutingStrategyLabel(
        repairResult.profile,
      )

      return {
        type: 'text',
        value: [
          `Auto-repaired profile ${repairResult.profile.name}:`,
          ...repairResult.repairLines,
          originalFamily === repairedFamily
            ? `Route family: ${repairedFamily} (unchanged)`
            : `Route family: ${originalFamily} -> ${repairedFamily}`,
          originalStrategy === repairedStrategy
            ? `Routing strategy: ${repairedStrategy} (unchanged)`
            : `Routing strategy: ${originalStrategy} -> ${repairedStrategy}`,
          profile.id === repairResult.profile.id
            ? 'Impact: updated and activated the saved profile.'
            : 'Impact: updated the live current API configuration.',
          `Next step: run \`${commandPrefix} validate\` to confirm the repaired route before relying on native workflows.`,
          ...repairResult.validation.lines,
          `Status: ${repairResult.validation.status}`,
        ].join('\n'),
      }
    }

    return {
      type: 'text',
      value: [
        `No automatic repair was applied for ${profile.name}.`,
        ...repairResult.originalValidation.lines,
        `Status: ${repairResult.validation.status}`,
        `Next step: adjust the route within the same family first, then run \`${commandPrefix} validate\` again.`,
      ].join('\n'),
    }
  }

  if (trimmedArgs === 'setup' || trimmedArgs === 'login') {
    return {
      type: 'text',
      value: getDefaultSetupHintLine(commandPrefix),
    }
  }

  const useMatch = trimmedArgs.match(/^(use|activate)\s+(.+)$/i)
  const profileQuery = useMatch?.[2]?.trim() || trimmedArgs

  if (
    profileQuery === CURRENT_PROVIDER_PROFILE_ID ||
    profileQuery.toLowerCase() === 'current' ||
    profileQuery.toLowerCase() === 'current api config'
  ) {
    const activatedProfile = activateCurrentProviderProfile()
    if (!activatedProfile) {
      return {
        type: 'text',
        value: 'The current API configuration is no longer available.',
      }
    }

    syncLiveSession(context, activatedProfile)
    return {
      type: 'text',
      value: `Switched to the current API config\n${formatProviderSummary(
        activatedProfile,
      )}`,
    }
  }

  const matched = resolveSingleProviderMatch(profileQuery, commandPrefix)
  if ('error' in matched) {
    return {
      type: 'text',
      value: matched.error,
    }
  }

  const activatedProfile = activateProviderProfile(matched.profile.id)
  if (!activatedProfile) {
    return {
      type: 'text',
      value: `Profile '${matched.profile.name}' is no longer available.`,
    }
  }

  syncLiveSession(context, activatedProfile)
  return {
    type: 'text',
    value: `Activated profile ${activatedProfile.name}\n${formatProviderSummary(
      activatedProfile,
    )}`,
  }
}
