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

const { InputSpec, Value } = sdk

const inputSpec = InputSpec.of({
  whisper_base_url: Value.text({
    name: 'Whisper Base URL',
    description:
      "URL of your Whisper-compatible transcription server. Example: http://whisper.startos:8000 for a local StartOS package, or http://192.168.1.10:9000 for whisper.cpp running on another machine on your LAN. The endpoint must implement OpenAI's /v1/audio/transcriptions wire format.",
    required: true,
    default: null,
    minLength: 1,
    maxLength: 512,
    patterns: [
      {
        regex: '^https?://.+',
        description: 'Must start with http:// or https://',
      },
    ],
  }),
  whisper_api_key: Value.text({
    name: 'API Key (optional)',
    description:
      'API key for the Whisper backend. Most self-hosted Whisper servers (whisper.cpp HTTP server, faster-whisper-server) accept any value or none at all — leave blank for those. Cloud Whisper providers (Groq, etc.) require a real key.',
    required: false,
    default: null,
    masked: true,
    minLength: 0,
    maxLength: 256,
  }),
})

export const setWhisperEndpoint = sdk.Action.withInput(
  'set-whisper-endpoint',

  async ({ effects }) => ({
    name: 'Set Whisper Endpoint',
    description:
      'Point Recaps at a self-hosted or third-party Whisper transcription server (whisper.cpp, faster-whisper-server, Groq, etc.). Free alternative to OpenAI Whisper API or Gemini multimodal transcription.',
    warning: null,
    allowedStatuses: 'any',
    group: 'AI Providers',
    visibility: 'enabled',
  }),

  inputSpec,

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

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