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

const { InputSpec, Value } = sdk

// Standard Ollama port. Hardcoded because Ollama upstream uses 11434
// universally — its StartOS package preserves this. If a future
// release changes the port we can swap to a runtime
// sdk.serviceInterface.get(...) lookup against ollama's exposed
// interface, but for now hardcode + override-on-mismatch is simpler
// and avoids a guess at the interface ID.
const OLLAMA_DEFAULT_PORT = 11434

const inputSpec = InputSpec.of({
  ollama_base_url: Value.text({
    name: 'Ollama Base URL',
    description:
      'URL of your Ollama server. If you have the Ollama StartOS package installed on this server, this field is pre-populated automatically. Override only if you want to point at a different Ollama instance (e.g. on another machine: http://192.168.1.10:11434).',
    required: false,
    default: 'http://localhost:11434',
    minLength: 0,
    maxLength: 256,
    patterns: [
      {
        regex: '^(https?://.+)?$',
        description: 'Must be empty or start with http:// or https://',
      },
    ],
  }),
})

// Best-effort detection of an Ollama instance running on this same
// StartOS server. StartOS exposes every package on its own internal
// `<package-id>.startos` hostname, reachable from any other package's
// container without explicit networking config (per the Service
// Packaging docs). Returns the URL when ollama is installed, null
// otherwise.
async function detectStartOsOllamaUrl(effects: any): Promise<string | null> {
  try {
    const check = await sdk.checkDependencies(effects, ['ollama'])
    if (!check.installedSatisfied('ollama')) return null
    return `http://ollama.startos:${OLLAMA_DEFAULT_PORT}`
  } catch {
    return null
  }
}

export const setOllamaUrl = sdk.Action.withInput(
  'set-ollama-url',

  async ({ effects }) => ({
    name: 'Set Ollama Server URL',
    description:
      'Configure where to reach a local Ollama server for topic analysis. No API key required (Ollama runs locally). Does not transcribe audio. Auto-pre-populates if the Ollama StartOS package is installed on this server.',
    warning: null,
    allowedStatuses: 'any',
    group: 'AI Providers',
    visibility: 'enabled',
  }),

  inputSpec,

  async ({ effects }) => {
    const config = await configFile.read().once()
    // If the user has already set a value, respect it — don't
    // overwrite a manual override on every action open.
    if (config?.ollama_base_url) {
      return { ollama_base_url: config.ollama_base_url }
    }
    const auto = await detectStartOsOllamaUrl(effects)
    if (auto) return { ollama_base_url: auto }
    return { ollama_base_url: 'http://localhost:11434' }
  },

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