File size: 9,509 Bytes
894fa47
 
 
 
 
 
 
 
 
 
 
 
8c4a8b2
 
 
 
894fa47
 
 
 
 
 
 
 
 
 
 
 
 
4b5364e
 
894fa47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ee5617c
 
 
894fa47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1dc8acc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
894fa47
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
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
// ===== ENVIRONMENT-AWARE API URL DETECTION =====
function getBaseUrl(): string {
  // Priority 1: Check localStorage for user-set ngrok URL
  const storedBackendUrl = localStorage.getItem('backend_url');
  if (storedBackendUrl) {
    console.log('βœ… Using stored backend URL:', storedBackendUrl);
    return storedBackendUrl;
  }

  // Priority 2: Check environment variable
  if (typeof import.meta.env.VITE_BACKEND_URL !== 'undefined' && import.meta.env.VITE_BACKEND_URL) {
    const envUrl = import.meta.env.VITE_BACKEND_URL;
    // Add /api suffix if not present
    const finalUrl = envUrl.endsWith('/api') ? envUrl : `${envUrl.replace(/\/$/, '')}/api`;
    console.log('βœ… Using VITE_BACKEND_URL:', finalUrl);
    return finalUrl;
  }

  // Priority 3: Check if running on local development
  const hostname = window.location.hostname;
  const isLocalhost = hostname === 'localhost' || hostname === '127.0.0.1';
  const isLocalDomain = hostname.includes('local') || hostname.includes('10.7.');

  if (isLocalhost || isLocalDomain) {
    console.log('βœ… Running on local, using localhost:8000/api');
    return 'http://localhost:8000/api';
  }

  // Priority 4: Production fallback
  console.log('☁️ Running on production domain - using Hugging Face backend');
  return 'https://kimaan28-cytosight.hf.space/api';
}

function getCurrentBaseUrl(): string {
  return getBaseUrl();
}

export function setBackendUrl(url: string) {
  localStorage.setItem('backend_url', url);
  console.log('βœ… Backend URL updated to:', url);
  console.log('πŸ”„ Refresh page or make API call for changes to take effect');
}

type HttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";

export async function apiCall<T = unknown>(
  method: HttpMethod,
  endpoint: string,
  body?: unknown,
  token?: string
): Promise<T> {
  const authToken = token ?? getToken();

  const headers: Record<string, string> = {
    "Content-Type": "application/json",
  };

  if (authToken) {
    headers.Authorization = `Bearer ${authToken}`;
  }

  const baseUrl = getCurrentBaseUrl();
  const url = `${baseUrl}${endpoint}`;
  
  try {
    console.log(`[API Request] ${method} ${url}`);
    
    const res = await fetch(url, {
      method,
      headers,
      credentials: 'include',
      body: body === undefined ? undefined : JSON.stringify(body),
    });

    console.log(`[API Response] ${method} ${url} - Status ${res.status}`);

    if (!res.ok) {
      let errorMessage = `HTTP ${res.status}`;
      
      try {
        const error = await res.json();
        errorMessage = error.detail || errorMessage;
      } catch {
        errorMessage = res.statusText || errorMessage;
      }

      if (res.status === 401) {
        errorMessage = "Unauthorized - Please login again";
      } else if (res.status === 403) {
        errorMessage = "Forbidden - You don't have permission";
      } else if (res.status === 404) {
        errorMessage = "Resource not found";
      } else if (res.status === 500) {
        errorMessage = "Server error - Backend may not be running";
      }

      console.error(`[API Error] ${errorMessage}`);
      throw new Error(errorMessage);
    }

    if (res.status === 204) {
      return undefined as T;
    }

    const data = await res.json();
    console.log(`[API Success] ${method} ${url}`);
    return data;
  } catch (error) {
    if (error instanceof TypeError) {
      if (error.message.includes('Failed to fetch')) {
        const helpMsg = 'Failed to reach backend. Make sure:\n1. Backend is running\n2. ngrok tunnel is active\n3. ngrok URL is correct in localStorage';
        console.error(`[CORS/Network Error] ${helpMsg}`);
        throw new Error(helpMsg);
      }
    }
    
    console.error(`[API Error] ${method} ${url}`, error);
    throw error;
  }
}

// βœ… FIXED: signup and login now use proper apiCall with credentials
export async function signup({ 
  fullName, 
  email, 
  password 
}: { 
  fullName: string; 
  email: string; 
  password: string;
}) {
  const cleanEmail = email.trim();
  const cleanPassword = password.trim();
  
  const baseUrl = getCurrentBaseUrl();
  
  try {
    console.log('[SIGNUP] Attempting signup...');
    const res = await fetch(`${baseUrl}/auth/signup`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      credentials: 'include', // βœ… Critical for CORS
      body: JSON.stringify({
        full_name: fullName.trim(),
        email: cleanEmail,
        password: cleanPassword,
      }),
    });
    
    if (!res.ok) {
      const error = await res.json().catch(() => ({}));
      throw new Error(error.detail || "Signup failed");
    }
    
    const data = await res.json();
    console.log('[SIGNUP] Success');
    
    if (data.access_token) {
      localStorage.setItem('access_token', data.access_token);
      localStorage.setItem('refresh_token', data.refresh_token);
      localStorage.setItem('user', JSON.stringify(data.user));
    }
    
    return data;
  } catch (err) {
    console.error('[SIGNUP] Error:', err);
    throw err;
  }
}

export async function login({ 
  email, 
  password 
}: { 
  email: string; 
  password: string;
}) {
  const cleanEmail = email.trim();
  const cleanPassword = password.trim();
  
  const baseUrl = getCurrentBaseUrl();
  
  try {
    console.log('[LOGIN] Attempting login...');
    const res = await fetch(`${baseUrl}/auth/login`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      credentials: 'include', // βœ… Critical for CORS
      body: JSON.stringify({
        email: cleanEmail,
        password: cleanPassword,
      }),
    });
    
    if (!res.ok) {
      const error = await res.json().catch(() => ({}));
      throw new Error(error.detail || "Login failed");
    }
    
    const data = await res.json();
    console.log('[LOGIN] Success');
    
    if (data.access_token) {
      localStorage.setItem('access_token', data.access_token);
      localStorage.setItem('refresh_token', data.refresh_token);
      localStorage.setItem('user', JSON.stringify(data.user));
    }
    
    return data;
  } catch (err) {
    console.error('[LOGIN] Error:', err);
    throw err;
  }
}

export async function uploadImage({ 
  file, 
  token 
}: { 
  file: File; 
  token: string;
}) {
  const formData = new FormData();
  formData.append("file", file);

  const res = await fetch(`${getCurrentBaseUrl()}/upload/image`, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${token}`,
    },
    credentials: 'include',
    body: formData,
  });
  
  if (!res.ok) {
    const error = await res.json().catch(() => ({}));
    throw new Error(error.detail || "Image upload failed");
  }
  
  return res.json();
}

export async function runDiagnosis({
  imagePath,
  imageUrl,
  token
}: {
  imagePath?: string;
  imageUrl?: string;
  token: string;
}) {
  const res = await fetch(`${getCurrentBaseUrl()}/diagnosis/predict`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${token}`,
    },
    credentials: 'include',
    body: JSON.stringify({
      image_file_path: imagePath,
      image_url: imageUrl,
    }),
  });

  if (!res.ok) {
    const error = await res.json().catch(() => ({}));
    throw new Error(error.detail || "Diagnosis failed");
  }

  return res.json();
}

export async function runSegmentation({
  imagePath,
  imageUrl,
  token,
}: {
  imagePath?: string;
  imageUrl?: string;
  token: string;
}) {
  const res = await fetch(`${getCurrentBaseUrl()}/segmentation/predict`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${token}`,
    },
    credentials: "include",
    body: JSON.stringify({
      image_file_path: imagePath,
      image_url: imageUrl,
    }),
  });

  if (!res.ok) {
    const error = await res.json().catch(() => ({}));
    throw new Error(error.detail || "Segmentation failed");
  }

  return res.json();
}

export async function fetchExplainability({
  imageUrl,
  diagnosisData,
  token,
}: {
  imageUrl: string;
  diagnosisData: any;
  token?: string;
}) {
  return apiCall<{
    attention_heatmap_base64: string;
    attention_bbox_base64: string;
    highest_attention_crop_base64: string;
    zone_reference_base64: string;
    gpt_statement: string;
  }>("POST", "/explain", {
    image_url: imageUrl,
    diagnosis_data: diagnosisData,
  }, token);
}

// Token helpers
export function getToken(): string | null {
  return localStorage.getItem('access_token');
}

export function getRefreshToken(): string | null {
  return localStorage.getItem('refresh_token');
}

export function getCurrentUser() {
  const userStr = localStorage.getItem('user');
  return userStr ? JSON.parse(userStr) : null;
}

export function isLoggedIn(): boolean {
  return !!localStorage.getItem('access_token');
}

export function logout() {
  localStorage.removeItem('access_token');
  localStorage.removeItem('refresh_token');
  localStorage.removeItem('user');
  console.log('[LOGOUT] User logged out');
}

export async function clearAllHistory(token: string) {
  const res = await fetch(`${getCurrentBaseUrl()}/diagnosis/history`, {
    method: "DELETE",
    headers: {
      Authorization: `Bearer ${token}`,
    },
    credentials: "include",
  });

  if (!res.ok) {
    const error = await res.json().catch(() => ({}));
    throw new Error(error.detail || "Failed to clear history");
  }

  return res.json();
}