/**
 * Production settings check (task T9, the Brain CTO's question W3).
 *
 * Reports only WHETHER each setting is present, never its value, so anyone
 * holding the cron secret can confirm production without seeing a secret.
 * `brain_credential_in_use` names which credential the Brain calls would send
 * today, so the shared-token fallback can be removed safely (task T10).
 */
export const CHECKED_SETTINGS = [
  'HHA_API_BASE_URL',
  'HHA_API_CLIENT_ID',
  'HHA_API_CLIENT_SECRET',
  'HHA_WORKSPACE_SYNC_TOKEN',
  'FLASK_API_KEY',
  'SYNCHRON_CALLBACK_SECRET',
  'CRON_SECRET',
  'NEXT_PUBLIC_APP_URL',
  'AWS_ACCESS_KEY_ID',
  'AWS_SECRET_ACCESS_KEY',
  'S3_BUCKET_NAME',
  'DEV_TASKS_API_KEY_HASHES',
] as const

export type BrainCredential = 'client_secret' | 'workspace_sync_token_fallback' | 'flask_api_key_fallback' | 'none'

type Env = Record<string, string | undefined>

const present = (env: Env, key: string) => Boolean(env[key]?.trim())

/** Same order as the Brain adapter (src/lib/adapters/flask.ts). */
export function brainCredentialInUse(env: Env): BrainCredential {
  if (present(env, 'HHA_API_CLIENT_SECRET')) return 'client_secret'
  if (present(env, 'HHA_WORKSPACE_SYNC_TOKEN')) return 'workspace_sync_token_fallback'
  if (present(env, 'FLASK_API_KEY')) return 'flask_api_key_fallback'
  return 'none'
}

export function settingsReport(env: Env) {
  const settings = Object.fromEntries(CHECKED_SETTINGS.map((key) => [key, present(env, key)])) as Record<(typeof CHECKED_SETTINGS)[number], boolean>
  const credential = brainCredentialInUse(env)
  return {
    settings,
    brain_credential_in_use: credential,
    // T10 may ship only when this is true: the Brain calls already use the
    // Workspace's own credential, so removing the fallbacks changes nothing.
    ready_to_remove_shared_token_fallback: credential === 'client_secret' && present(env, 'HHA_API_CLIENT_ID'),
  }
}
