import { sdk } from '../sdk'
import { configFile } from '../file-models/config.json'

const { InputSpec, Value } = sdk

const inputSpec = InputSpec.of({
  openai_api_key: Value.text({
    name: 'OpenAI API Key',
    description:
      'Your OpenAI API key. Get one at platform.openai.com. Used for both topic analysis (GPT models) and audio transcription (Whisper).',
    required: true,
    default: null,
    masked: true,
    minLength: 1,
    maxLength: 256,
  }),
})

export const setOpenAIApiKey = sdk.Action.withInput(
  'set-openai-api-key',

  async ({ effects }) => ({
    name: 'Set OpenAI API Key',
    description:
      'Configure your OpenAI API key. Enables GPT models for topic analysis and Whisper for audio transcription.',
    warning: null,
    allowedStatuses: 'any',
    group: 'AI Providers',
    visibility: 'enabled',
  }),

  inputSpec,

  async ({ effects }) => {
    const config = await configFile.read().once()
    return { openai_api_key: config?.openai_api_key || undefined }
  },

  async ({ effects, input }) => {
    await configFile.merge(effects, {
      openai_api_key: (input.openai_api_key || '').trim(),
    })
    return null
  },
)
