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88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
/**
 * FarmEyes API Client
 * ===================
 * Handles all communication with the FastAPI backend.
 * Provides clean async methods for detection, chat, and transcription.
 */

const FarmEyesAPI = {
    // Base URL - auto-detect based on environment
    baseUrl: window.location.origin,
    
    // Current session ID
    sessionId: null,
    
    // Current language
    language: 'en',
    
    /**
     * Initialize API client
     */
    async init() {
        // Try to get existing session from storage
        this.sessionId = localStorage.getItem('farmeyes_session');
        this.language = localStorage.getItem('farmeyes_language') || 'en';
        
        // Create new session if none exists
        if (!this.sessionId) {
            await this.createSession(this.language);
        }
        
        console.log('[API] Initialized with session:', this.sessionId?.substring(0, 8));
        return this;
    },
    
    /**
     * Make an API request
     * @param {string} endpoint - API endpoint
     * @param {object} options - Fetch options
     * @returns {Promise<object>} Response data
     */
    async request(endpoint, options = {}) {
        const url = `${this.baseUrl}${endpoint}`;
        
        const defaultOptions = {
            headers: {
                'Accept': 'application/json',
            },
        };
        
        // Merge options
        const fetchOptions = { ...defaultOptions, ...options };
        
        // Add Content-Type for JSON body
        if (options.body && !(options.body instanceof FormData)) {
            fetchOptions.headers['Content-Type'] = 'application/json';
            fetchOptions.body = JSON.stringify(options.body);
        }
        
        try {
            const response = await fetch(url, fetchOptions);
            
            // Handle non-JSON responses
            const contentType = response.headers.get('content-type');
            if (!contentType || !contentType.includes('application/json')) {
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                return { success: true };
            }
            
            const data = await response.json();
            
            if (!response.ok) {
                throw new Error(data.detail || data.error || `HTTP ${response.status}`);
            }
            
            return data;
        } catch (error) {
            console.error('[API] Request failed:', endpoint, error);
            throw error;
        }
    },
    
    // =========================================================================
    // SESSION MANAGEMENT
    // =========================================================================
    
    /**
     * Create a new session
     * @param {string} language - Language code
     * @returns {Promise<object>} Session data
     */
    async createSession(language = 'en') {
        const data = await this.request(`/api/session?language=${language}`);
        
        if (data.success && data.session_id) {
            this.sessionId = data.session_id;
            this.language = language;
            localStorage.setItem('farmeyes_session', this.sessionId);
            localStorage.setItem('farmeyes_language', language);
            console.log('[API] Session created:', this.sessionId.substring(0, 8));
        }
        
        return data;
    },
    
    /**
     * Get session info
     * @returns {Promise<object>} Session info
     */
    async getSession() {
        if (!this.sessionId) {
            return { success: false, error: 'No session' };
        }
        return this.request(`/api/session/${this.sessionId}`);
    },
    
    /**
     * Update session language
     * @param {string} language - New language code
     * @returns {Promise<object>} Updated session
     */
    async setLanguage(language) {
        if (!this.sessionId) {
            await this.createSession(language);
            return { success: true };
        }
        
        const data = await this.request(`/api/session/${this.sessionId}/language?language=${language}`, {
            method: 'PUT'
        });
        
        if (data.success) {
            this.language = language;
            localStorage.setItem('farmeyes_language', language);
        }
        
        return data;
    },
    
    /**
     * Clear current session and create new one
     * @returns {Promise<object>} New session data
     */
    async resetSession() {
        if (this.sessionId) {
            try {
                await this.request(`/api/session/${this.sessionId}`, { method: 'DELETE' });
            } catch (e) {
                // Ignore errors on delete
            }
        }
        
        localStorage.removeItem('farmeyes_session');
        this.sessionId = null;
        
        return this.createSession(this.language);
    },
    
    // =========================================================================
    // DISEASE DETECTION
    // =========================================================================
    
    /**
     * Analyze crop image for disease detection
     * @param {File} imageFile - Image file to analyze
     * @param {string} language - Language for results
     * @returns {Promise<object>} Detection results
     */
    async detectDisease(imageFile, language = null) {
        const formData = new FormData();
        formData.append('file', imageFile);
        formData.append('language', language || this.language);
        formData.append('session_id', this.sessionId || '');
        
        const data = await this.request('/api/detect/', {
            method: 'POST',
            body: formData
        });
        
        // Update session ID if returned
        if (data.session_id) {
            this.sessionId = data.session_id;
            localStorage.setItem('farmeyes_session', this.sessionId);
        }
        
        return data;
    },
    
    /**
     * Analyze base64 encoded image
     * @param {string} base64Image - Base64 encoded image
     * @param {string} language - Language for results
     * @returns {Promise<object>} Detection results
     */
    async detectDiseaseBase64(base64Image, language = null) {
        const data = await this.request('/api/detect/base64', {
            method: 'POST',
            body: {
                image_base64: base64Image,
                language: language || this.language,
                session_id: this.sessionId
            }
        });
        
        if (data.session_id) {
            this.sessionId = data.session_id;
            localStorage.setItem('farmeyes_session', this.sessionId);
        }
        
        return data;
    },
    
    /**
     * Get detection service status
     * @returns {Promise<object>} Service status
     */
    async getDetectionStatus() {
        return this.request('/api/detect/status');
    },
    
    /**
     * Get supported disease classes
     * @returns {Promise<object>} Classes info
     */
    async getClasses() {
        return this.request('/api/detect/classes');
    },
    
    /**
     * Clear current diagnosis
     * @returns {Promise<object>} Result
     */
    async clearDiagnosis() {
        if (!this.sessionId) {
            return { success: false, error: 'No session' };
        }
        return this.request(`/api/detect/session/${this.sessionId}`, {
            method: 'DELETE'
        });
    },
    
    // =========================================================================
    // CHAT
    // =========================================================================
    
    /**
     * Send chat message
     * @param {string} message - User message
     * @param {string} language - Response language
     * @returns {Promise<object>} Chat response
     */
    async sendChatMessage(message, language = null) {
        if (!this.sessionId) {
            await this.createSession(language || this.language);
        }
        
        return this.request('/api/chat/', {
            method: 'POST',
            body: {
                session_id: this.sessionId,
                message: message,
                language: language || this.language
            }
        });
    },
    
    /**
     * Get welcome message for chat
     * @param {string} language - Language code
     * @returns {Promise<object>} Welcome message
     */
    async getChatWelcome(language = null) {
        if (!this.sessionId) {
            return { success: false, error: 'No session' };
        }
        
        const lang = language || this.language;
        return this.request(`/api/chat/welcome?session_id=${this.sessionId}&language=${lang}`);
    },
    
    /**
     * Get chat history
     * @param {number} limit - Max messages to return
     * @returns {Promise<object>} Chat history
     */
    async getChatHistory(limit = 50) {
        if (!this.sessionId) {
            return { success: false, messages: [] };
        }
        
        return this.request(`/api/chat/history?session_id=${this.sessionId}&limit=${limit}`);
    },
    
    /**
     * Clear chat history
     * @returns {Promise<object>} Result
     */
    async clearChatHistory() {
        if (!this.sessionId) {
            return { success: false };
        }
        
        return this.request(`/api/chat/history?session_id=${this.sessionId}`, {
            method: 'DELETE'
        });
    },
    
    /**
     * Get current diagnosis context
     * @returns {Promise<object>} Diagnosis context
     */
    async getChatContext() {
        if (!this.sessionId) {
            return { success: false };
        }
        
        return this.request(`/api/chat/context?session_id=${this.sessionId}`);
    },
    
    // =========================================================================
    // VOICE TRANSCRIPTION
    // =========================================================================
    
    /**
     * Transcribe audio file
     * @param {File|Blob} audioFile - Audio file to transcribe
     * @param {string} languageHint - Language hint
     * @returns {Promise<object>} Transcription result
     */
    async transcribeAudio(audioFile, languageHint = null) {
        const formData = new FormData();
        formData.append('file', audioFile, audioFile.name || 'audio.wav');
        
        if (languageHint) {
            formData.append('language_hint', languageHint);
        }
        
        return this.request('/api/transcribe/', {
            method: 'POST',
            body: formData
        });
    },
    
    /**
     * Transcribe base64 audio
     * @param {string} base64Audio - Base64 encoded audio
     * @param {string} filename - Original filename
     * @param {string} languageHint - Language hint
     * @returns {Promise<object>} Transcription result
     */
    async transcribeBase64(base64Audio, filename = 'audio.wav', languageHint = null) {
        return this.request('/api/transcribe/base64', {
            method: 'POST',
            body: {
                audio_base64: base64Audio,
                filename: filename,
                language_hint: languageHint
            }
        });
    },
    
    /**
     * Get transcription service status
     * @returns {Promise<object>} Service status
     */
    async getTranscriptionStatus() {
        return this.request('/api/transcribe/status');
    },
    
    /**
     * Pre-load Whisper model
     * @returns {Promise<object>} Result
     */
    async loadWhisperModel() {
        return this.request('/api/transcribe/load-model', {
            method: 'POST'
        });
    },
    
    // =========================================================================
    // UI TRANSLATIONS
    // =========================================================================
    
    /**
     * Get UI translations
     * @param {string} language - Language code
     * @returns {Promise<object>} Translations
     */
    async getTranslations(language = null) {
        const lang = language || this.language;
        return this.request(`/api/translations?language=${lang}`);
    },
    
    // =========================================================================
    // HEALTH CHECK
    // =========================================================================
    
    /**
     * Check API health
     * @returns {Promise<object>} Health status
     */
    async healthCheck() {
        return this.request('/health');
    },
    
    /**
     * Get API info
     * @returns {Promise<object>} API information
     */
    async getApiInfo() {
        return this.request('/api');
    }
};

// Export for use in other modules
window.FarmEyesAPI = FarmEyesAPI;