import { invoke } from '@tauri-apps/api/core';
import {
  AgentConfigStatus,
  SaveAgentRuntimeConfigRequest,
  UpdateRemoteApiKeyRequest,
} from '../types/agentSettings';
import { assertAgentConfigStatus } from './agentConfigStatus';

class AgentSettingsBridge {
  async getStatus(): Promise<AgentConfigStatus> {
    try {
      const result = await invoke<unknown>('get_agent_config_status');
      assertAgentConfigStatus(result);
      return result;
    } catch (error) {
      console.error('[AgentSettingsBridge] Failed to load agent config status.');
      throw error;
    }
  }

  async saveRuntimeConfig(request: SaveAgentRuntimeConfigRequest): Promise<AgentConfigStatus> {
    try {
      const result = await invoke<unknown>('save_agent_runtime_config', { request });
      assertAgentConfigStatus(result);
      return result;
    } catch (error) {
      console.error('[AgentSettingsBridge] Failed to save agent runtime config.');
      throw error;
    }
  }

  async updateRemoteApiKey(request: UpdateRemoteApiKeyRequest): Promise<AgentConfigStatus> {
    try {
      const result = await invoke<unknown>('update_remote_api_key', { request });
      assertAgentConfigStatus(result);
      return result;
    } catch (error) {
      console.error('[AgentSettingsBridge] Failed to update remote API key.');
      throw error;
    }
  }

  async clearRemoteApiKey(): Promise<AgentConfigStatus> {
    try {
      const result = await invoke<unknown>('clear_remote_api_key');
      assertAgentConfigStatus(result);
      return result;
    } catch (error) {
      console.error('[AgentSettingsBridge] Failed to clear remote API key.');
      throw error;
    }
  }
}

export const agentSettingsBridge = new AgentSettingsBridge();
