// bot/src/commands/bot.ts — router central do comando /bot

import path from 'node:path'
import type { App } from '@slack/bolt'
import type { LLMProvider } from '../providers/llm/index'
import type { RepoProvider, WorkTrackerProvider } from '../providers/contracts'
import { handleHelp } from './help'
import { handleCreate } from './create'
import { handleUpdate } from './update'
import { handleAproved } from './aproved'
import { handleList } from './list'
import { handleView } from './view'

export interface BotCommandDeps {
  llm: LLMProvider
  workTrackerProvider: WorkTrackerProvider
  repoProvider?: RepoProvider
  /** Raiz do repositório — a worktree fica em <projectRoot>/.worktree/<cardId> */
  projectRoot: string
}

export function registerBotCommand(app: App, deps?: BotCommandDeps): void {
  app.command('/bot', async ({ command, ack, respond, client }) => {
    await ack()  // < 3s obrigatório

    const [sub, ...rest] = (command.text ?? '').trim().split(/\s+/)
    const args = rest.join(' ')

    void dispatch(sub?.toLowerCase(), args, command, respond, client, deps)
      .catch(err => {
        console.error('[/bot] erro não tratado:', redactSecrets(String(err)))
        void respond({ text: '❌ Erro interno. Tente novamente.' })
      })
  })
}

async function dispatch(
  sub: string | undefined,
  args: string,
  command: any,
  respond: any,
  client: any,
  deps?: BotCommandDeps,
): Promise<void> {
  switch (sub) {
    case 'create':  return handleCreate(
      args,
      command,
      respond,
      client,
      {
        llm:          deps!.llm,
        workTrackerProvider: deps!.workTrackerProvider,
        repoProvider: deps!.repoProvider,
        worktreePath: path.join(deps!.projectRoot, '.worktree'),
      },
    )
    case 'update':  return handleUpdate(args, command, respond, client, deps!.workTrackerProvider)
    case 'aproved': return handleAproved(args, command, respond, client, deps!.workTrackerProvider)
    case 'list':    return handleList(command, respond, client)
    case 'view':    return handleView(args, command, respond, client, deps!.workTrackerProvider)
    default:        return handleHelp(respond)
  }
}


export function redactSecrets(s: string): string {
  return s
    .replace(/(xox[bpas]-[\w-]+)/g, '[REDACTED]')
    .replace(/(xapp-\d-[\w-]+)/g, '[REDACTED]')
    .replace(/(Basic\s+[A-Za-z0-9+/=]+)/g, 'Basic [REDACTED]')
    .replace(/(ATATT[\w.\-]+)/g, '[REDACTED]')
    .replace(/\b(gh[posru]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,})\b/g, '[REDACTED]')
    .replace(/(Bearer\s+[\w.\-]+)/g, 'Bearer [REDACTED]')
    .replace(/(https?:\/\/)[^\s:@/]+:[^\s:@/]+@/g, '$1[REDACTED]@')
}
