// SPDX-License-Identifier: MIT
// Copyright (c) 2025-2026 SenWeaverCoding
// Licensed under the MIT License.

import { api } from './client'
import type {
  AutonomySettings,
  LoopControlsSettings,
  PermissionMode,
  UserSettings,
} from '../types/settings'

export type CliLauncherStatus = {
  supported: boolean
  command: string
  installed: boolean
  launcherPath: string
  binDir: string
  pathConfigured: boolean
  pathInCurrentShell: boolean
  availableInNewTerminals: boolean
  needsTerminalRestart: boolean
  configTarget: string | null
  lastError: string | null
}

export const settingsApi = {
  getUser() {
    return api.get<UserSettings>('/api/settings/user')
  },

  updateUser(settings: Partial<UserSettings>) {
    return api.put<{ ok: true }>('/api/settings/user', settings)
  },

  getPermissionMode() {
    return api.get<{ mode: PermissionMode }>('/api/permissions/mode')
  },

  setPermissionMode(mode: PermissionMode) {
    return api.put<{ ok: true; mode: PermissionMode }>('/api/permissions/mode', { mode })
  },

  getAutonomy() {
    return api.get<AutonomySettings>('/api/permissions/autonomy')
  },

  setAutonomy(patch: Partial<AutonomySettings>) {
    return api.put<AutonomySettings>('/api/permissions/autonomy', patch)
  },

  getLoopControls() {
    return api.get<LoopControlsSettings>('/api/agents/loop-controls')
  },

  setLoopControls(patch: Partial<LoopControlsSettings>) {
    return api.put<LoopControlsSettings>('/api/agents/loop-controls', patch)
  },

  getCliLauncherStatus() {
    return api.get<CliLauncherStatus>('/api/settings/cli-launcher')
  },

  exportSyncSnapshot() {
    return api.get<{ snapshot: unknown }>('/api/settings/sync/export')
  },

  importSyncSnapshot(snapshot: unknown) {
    return api.post<{ applied: unknown }>('/api/settings/sync/import', snapshot)
  },
}
