/**
 * Plain Node.js readline prompt for z.ai API key.
 * Runs BEFORE any Ink/React rendering to avoid keybinding conflicts.
 */
import * as readline from 'node:readline'
import { isZaiProvider } from './model/providers.js'
import { getGlobalConfig, saveGlobalConfig } from './config.js'

/**
 * If z.ai is the provider and no API key is configured yet,
 * prompt the user via plain stdin/stdout and save it.
 * Returns true if setup was performed.
 */
export async function promptZaiApiKeyIfNeeded(): Promise<boolean> {
  // Check if already configured via env
  if (process.env.ANTHROPIC_AUTH_TOKEN || process.env.ANTHROPIC_API_KEY) return false

  const config = getGlobalConfig()

  // Already has a z.ai key saved
  if (config.zaiApiKey) return false

  // Show prompt if: z.ai provider is explicitly set, OR this is first run (no provider configured)
  // SANDCODE defaults to z.ai, so first-run users need the key prompt.
  const needsSetup = isZaiProvider() || !config.provider
  if (!needsSetup) return false

  // Don't prompt in non-interactive mode (piped stdin, --print, etc.)
  if (!process.stdin.isTTY) return false

  console.log('')
  console.log('      \x1b[33m▜▀▀▀▀▀▛\x1b[0m')
  console.log('      \x1b[33m ▜░░░▛ \x1b[0m')
  console.log('      \x1b[33m  ▐▓▌  \x1b[0m')
  console.log('      \x1b[33m ▟▓▓▓▙ \x1b[0m')
  console.log('      \x1b[33m▙▄▄▄▄▄▟\x1b[0m')
  console.log('')
  console.log('  \x1b[1m\x1b[33mSANDCODE\x1b[0m — z.ai Setup')
  console.log('')
  console.log('  No z.ai API key found.')
  console.log('  Get one at: \x1b[4mhttps://z.ai\x1b[0m')
  console.log('')

  const key = await askForInput('  API Key > ')

  if (!key || key.trim().length === 0) {
    console.log('  No key entered. You can set it later with ANTHROPIC_AUTH_TOKEN env var.')
    return false
  }

  const trimmed = key.trim()

  saveGlobalConfig(current => ({
    ...current,
    provider: 'zai',
    zaiApiKey: trimmed,
    env: {
      ...current.env,
      ZAI_API_KEY: trimmed,
      SANDCODE_USE_ZAI: '1',
      API_TIMEOUT_MS: '3000000',
      ANTHROPIC_DEFAULT_OPUS_MODEL: 'GLM-5.1',
      ANTHROPIC_DEFAULT_SONNET_MODEL: 'GLM-5.1',
      ANTHROPIC_DEFAULT_HAIKU_MODEL: 'glm-4.5-air',
    },
  }))

  // Also set in current process so the rest of startup can use it
  process.env.ZAI_API_KEY = trimmed
  process.env.SANDCODE_USE_ZAI = '1'

  console.log('')
  console.log('  \x1b[32m✓\x1b[0m API key saved. Starting \x1b[33mSANDCODE\x1b[0m...')
  console.log('')

  return true
}

function askForInput(prompt: string): Promise<string> {
  return new Promise(resolve => {
    const rl = readline.createInterface({
      input: process.stdin,
      output: process.stdout,
    })
    rl.question(prompt, answer => {
      rl.close()
      resolve(answer)
    })
  })
}
