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

class AgentSettingsBridge {
  async getStatus(): Promise<AgentConfigStatus> {
    try {
      console.log('[AgentSettingsBridge] Fetching agent config status...');
      const result = await invoke<AgentConfigStatus>('get_agent_config_status');
      console.log('[AgentSettingsBridge] Received agent config status:', JSON.stringify(result, null, 2));

      // Validate the response structure
      this.validateAgentConfigStatus(result);

      return result;
    } catch (error) {
      console.error('[AgentSettingsBridge] Error in getStatus:', error);
      console.error('[AgentSettingsBridge] Error details:', {
        message: error instanceof Error ? error.message : String(error),
        stack: error instanceof Error ? error.stack : undefined,
      });
      throw error;
    }
  }

  async saveRuntimeConfig(request: SaveAgentRuntimeConfigRequest): Promise<AgentConfigStatus> {
    try {
      console.log('[AgentSettingsBridge] Saving runtime config:', JSON.stringify(request, null, 2));
      const result = await invoke<AgentConfigStatus>('save_agent_runtime_config', { request });
      console.log('[AgentSettingsBridge] Saved config, received status:', JSON.stringify(result, null, 2));

      // Validate the response structure
      this.validateAgentConfigStatus(result);

      return result;
    } catch (error) {
      console.error('[AgentSettingsBridge] Error in saveRuntimeConfig:', error);
      console.error('[AgentSettingsBridge] Request that failed:', JSON.stringify(request, null, 2));
      console.error('[AgentSettingsBridge] Error details:', {
        message: error instanceof Error ? error.message : String(error),
        stack: error instanceof Error ? error.stack : undefined,
      });
      throw error;
    }
  }

  async updateRemoteApiKey(request: UpdateRemoteApiKeyRequest): Promise<AgentConfigStatus> {
    try {
      console.log('[AgentSettingsBridge] Updating remote API key...');
      const result = await invoke<AgentConfigStatus>('update_remote_api_key', { request });
      console.log('[AgentSettingsBridge] Updated API key, received status:', JSON.stringify(result, null, 2));

      // Validate the response structure
      this.validateAgentConfigStatus(result);

      return result;
    } catch (error) {
      console.error('[AgentSettingsBridge] Error in updateRemoteApiKey:', error);
      console.error('[AgentSettingsBridge] Error details:', {
        message: error instanceof Error ? error.message : String(error),
        stack: error instanceof Error ? error.stack : undefined,
      });
      throw error;
    }
  }

  async clearRemoteApiKey(): Promise<AgentConfigStatus> {
    try {
      console.log('[AgentSettingsBridge] Clearing remote API key...');
      const result = await invoke<AgentConfigStatus>('clear_remote_api_key');
      console.log('[AgentSettingsBridge] Cleared API key, received status:', JSON.stringify(result, null, 2));

      // Validate the response structure
      this.validateAgentConfigStatus(result);

      return result;
    } catch (error) {
      console.error('[AgentSettingsBridge] Error in clearRemoteApiKey:', error);
      console.error('[AgentSettingsBridge] Error details:', {
        message: error instanceof Error ? error.message : String(error),
        stack: error instanceof Error ? error.stack : undefined,
      });
      throw error;
    }
  }

  private validateAgentConfigStatus(status: any): asserts status is AgentConfigStatus {
    console.log('[AgentSettingsBridge] Validating AgentConfigStatus structure...');

    if (!status || typeof status !== 'object') {
      throw new Error('Invalid AgentConfigStatus: not an object');
    }

    if (typeof status.configured !== 'boolean') {
      console.error('[AgentSettingsBridge] Invalid configured field:', status.configured);
      throw new Error('Invalid AgentConfigStatus: configured must be a boolean');
    }

    if (!status.providers || typeof status.providers !== 'object') {
      console.error('[AgentSettingsBridge] Invalid providers field:', status.providers);
      throw new Error('Invalid AgentConfigStatus: providers must be an object');
    }

    if (!status.providers.remote || typeof status.providers.remote !== 'object') {
      console.error('[AgentSettingsBridge] Invalid providers.remote field:', status.providers.remote);
      throw new Error('Invalid AgentConfigStatus: providers.remote must be an object');
    }

    if (!status.providers.ollama || typeof status.providers.ollama !== 'object') {
      console.error('[AgentSettingsBridge] Invalid providers.ollama field:', status.providers.ollama);
      throw new Error('Invalid AgentConfigStatus: providers.ollama must be an object');
    }

    if (!status.taskDefaults || typeof status.taskDefaults !== 'object') {
      console.error('[AgentSettingsBridge] Invalid taskDefaults field:', status.taskDefaults);
      throw new Error('Invalid AgentConfigStatus: taskDefaults must be an object');
    }

    if (typeof status.hasSecEdgarUserAgent !== 'boolean') {
      console.error('[AgentSettingsBridge] Invalid hasSecEdgarUserAgent field:', status.hasSecEdgarUserAgent);
      throw new Error('Invalid AgentConfigStatus: hasSecEdgarUserAgent must be a boolean');
    }

    if (typeof status.secEdgarUserAgent !== 'string') {
      console.error('[AgentSettingsBridge] Invalid secEdgarUserAgent field:', status.secEdgarUserAgent);
      throw new Error('Invalid AgentConfigStatus: secEdgarUserAgent must be a string');
    }

    console.log('[AgentSettingsBridge] AgentConfigStatus validation passed');
  }
}

export const agentSettingsBridge = new AgentSettingsBridge();
