// Debug version of Ollama Client to isolate fetch issues

export class OllamaClientDebug {
  private apiKey: string | null = null
  private baseURL: string

  constructor(apiKey?: string) {
    console.log('🔍 Debug: Initializing OllamaClient with key:', apiKey ? 'provided' : 'none')
    this.apiKey = apiKey || process.env.OLLAMA_API_KEY || null
    this.baseURL = 'https://ollama.com'
    
    if (this.apiKey) {
      console.log('✅ Debug: API key initialized, length:', this.apiKey.length)
      console.log('🔍 Debug: API key chars:', this.apiKey.split('').map(c => c.charCodeAt(0)))
    }
  }

  isAvailable(): boolean {
    console.log('🔍 Debug: Checking availability, key exists:', !!this.apiKey)
    return !!this.apiKey
  }

  // Get API key info
  getApiKeyInfo(): { isSet: boolean; source: string } {
    if (this.apiKey) {
      return {
        isSet: true,
        source: 'constructor'
      }
    }
    
    // Check localStorage
    const storedKey = typeof window !== 'undefined' ? localStorage.getItem('ollama_api_key') : null
    if (storedKey) {
      return {
        isSet: true,
        source: 'localStorage'
      }
    }

    return {
      isSet: false,
      source: 'none'
    }
  }

  async listModels() {
    console.log('🔍 Debug: Attempting to list models...')
    
    if (!this.isAvailable()) {
      console.error('❌ Debug: API key not available')
      throw new Error('Ollama API key not available')
    }

    try {
      console.log('🔍 Debug: Making request to:', `${this.baseURL}/api/tags`)
      
      // Create headers object first
      const headers: Record<string, string> = {
        'Content-Type': 'application/json',
      }
      
      // Add Authorization header if key exists
      if (this.apiKey) {
        headers['Authorization'] = `Bearer ${this.apiKey?.replace(/[^\x20-\x7E]/g, '').trim() || ''}`
        console.log('✅ Debug: Authorization header set, length:', headers['Authorization'].length)
      }
      
      console.log('🔍 Debug: Headers object:', headers)
      
      const response = await fetch(`${this.baseURL}/api/tags`, {
        method: 'GET',
        headers: headers,
      })

      console.log('🔍 Debug: Response status:', response.status)
      console.log('🔍 Debug: Response ok:', response.ok)

      if (!response.ok) {
        console.error('❌ Debug: Failed to list models:', response.statusText, response.status)
        throw new Error(`Failed to list models: ${response.statusText}`)
      }

      const data = await response.json()
      console.log('✅ Debug: Models retrieved:', data.models?.length || 0)
      return data.models
    } catch (error) {
      console.error('❌ Debug: Error in listModels:', error)
      throw error
    }
  }

  async chat(request: { model?: string; messages: any[]; stream?: boolean; options?: any }) {
    console.log('🔍 Debug: Starting chat with model:', request.model || 'default')
    
    if (!this.isAvailable()) {
      console.error('❌ Debug: API key not available for chat')
      throw new Error('Ollama API key not available')
    }

    try {
      console.log('🔍 Debug: Making chat request to:', `${this.baseURL}/api/chat`)
      
      // Create headers object first
      const headers: Record<string, string> = {
        'Content-Type': 'application/json',
      }
      
      // Add Authorization header if key exists
      if (this.apiKey) {
        headers['Authorization'] = `Bearer ${this.apiKey?.replace(/[^\x20-\x7E]/g, '').trim() || ''}`
        console.log('✅ Debug: Chat Authorization header set')
      }
      
      console.log('🔍 Debug: Chat headers:', headers)
      
      const response = await fetch(`${this.baseURL}/api/chat`, {
        method: 'POST',
        headers: headers,
        body: JSON.stringify({
          model: request.model || 'gpt-oss:120b-cloud',
          messages: request.messages,
          stream: false,
          options: {
            temperature: 0.7,
            top_p: 0.9,
            max_tokens: 1500,
            ...request.options,
          },
        }),
      })

      console.log('🔍 Debug: Chat response status:', response.status)
      console.log('🔍 Debug: Chat response ok:', response.ok)

      if (!response.ok) {
        console.error('❌ Debug: Chat failed:', response.statusText)
        throw new Error(`Ollama chat failed: ${response.statusText}`)
      }

      const data = await response.json()
      console.log('✅ Debug: Chat response received')
      return data.message?.content || 'No content received'
    } catch (error) {
      console.error('❌ Debug: Error in chat:', error)
      throw error
    }
  }
}

export const ollamaClientDebug = new OllamaClientDebug()

// Available cloud models
export const OLLAMA_CLOUD_MODELS = {
  'gpt-oss:120b-cloud': 'GPT-OSS 120B Cloud',
  'llama3.1:70b': 'Llama 3.1 70B',
  'llama3.1:8b': 'Llama 3.1 8B',
  'mixtral:8x7b': 'Mixtral 8x7B',
  'codellama:70b': 'CodeLlama 70B',
  'qwen2.5:72b': 'Qwen2.5 72B',
}