File size: 130,121 Bytes
dcbfea9
 
 
 
14f50a3
dcbfea9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14f50a3
dcbfea9
 
8a5c351
dcbfea9
 
 
8a5c351
dcbfea9
 
 
8a5c351
dcbfea9
 
 
8a5c351
dcbfea9
 
8a5c351
dcbfea9
8a5c351
dcbfea9
 
 
 
 
8a5c351
dcbfea9
 
8a5c351
dcbfea9
 
8a5c351
14f50a3
 
 
 
 
 
 
 
 
 
 
 
dcbfea9
 
8a5c351
dcbfea9
8a5c351
dcbfea9
 
 
8a5c351
dcbfea9
 
 
 
 
8a5c351
dcbfea9
 
 
6932d0d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dcbfea9
 
6932d0d
dcbfea9
6932d0d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8babf7e
 
 
 
 
 
14f50a3
 
 
 
8babf7e
 
 
 
 
 
 
 
 
 
 
 
14f50a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8babf7e
dcbfea9
 
 
8a5c351
dcbfea9
 
 
 
 
 
 
 
 
8a5c351
dcbfea9
 
 
 
 
 
 
 
8a5c351
 
dcbfea9
 
 
 
 
 
 
 
 
 
 
8a5c351
 
dcbfea9
 
 
 
 
 
 
 
 
 
 
 
 
 
8a5c351
 
dcbfea9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a5c351
 
dcbfea9
8a5c351
 
dcbfea9
 
 
 
 
 
 
 
 
 
 
8a5c351
 
dcbfea9
 
 
 
 
 
 
 
 
 
 
 
 
 
8a5c351
 
dcbfea9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a5c351
 
dcbfea9
8a5c351
 
dcbfea9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a5c351
 
dcbfea9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a5c351
dcbfea9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a5c351
 
dcbfea9
8a5c351
 
dcbfea9
 
 
 
 
 
 
 
 
 
 
 
8a5c351
 
dcbfea9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a5c351
 
dcbfea9
 
 
 
 
 
 
 
 
 
 
8a5c351
dcbfea9
 
 
 
8a5c351
dcbfea9
 
 
 
8a5c351
dcbfea9
8a5c351
 
dcbfea9
 
 
 
 
 
 
 
8a5c351
 
14f50a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dcbfea9
 
 
 
 
 
8a5c351
dcbfea9
 
 
8a5c351
dcbfea9
8a5c351
dcbfea9
 
8a5c351
dcbfea9
 
 
 
 
 
 
 
 
 
 
 
 
 
8a5c351
dcbfea9
 
 
 
 
 
 
 
8a5c351
dcbfea9
 
8a5c351
dcbfea9
 
 
 
 
 
 
 
 
8a5c351
dcbfea9
8a5c351
dcbfea9
 
 
8a5c351
dcbfea9
 
 
8a5c351
dcbfea9
 
 
 
 
 
 
 
 
 
8a5c351
dcbfea9
 
 
 
 
 
 
8a5c351
dcbfea9
 
 
 
 
 
 
8a5c351
dcbfea9
 
 
8a5c351
dcbfea9
8a5c351
dcbfea9
 
 
 
 
 
 
 
8a5c351
 
dcbfea9
 
 
 
 
 
 
 
 
8a5c351
 
dcbfea9
 
8a5c351
 
dcbfea9
 
 
 
 
 
 
 
 
 
 
 
 
8a5c351
 
dcbfea9
 
 
 
 
 
8a5c351
 
dcbfea9
 
8a5c351
dcbfea9
 
 
 
 
 
8a5c351
dcbfea9
 
 
 
 
 
 
 
 
 
 
 
 
 
8a5c351
dcbfea9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a5c351
 
dcbfea9
 
 
 
 
 
 
 
 
 
 
8a5c351
 
 
dcbfea9
 
 
8a5c351
 
dcbfea9
 
 
 
8a5c351
 
dcbfea9
 
 
 
 
 
 
 
 
 
8a5c351
dcbfea9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a5c351
dcbfea9
 
 
 
 
 
 
 
 
 
 
 
8a5c351
dcbfea9
8a5c351
 
dcbfea9
 
 
 
 
8a5c351
 
dcbfea9
 
 
 
 
8a5c351
 
dcbfea9
 
 
 
 
 
 
 
 
 
 
 
 
8a5c351
dcbfea9
 
8a5c351
 
dcbfea9
 
 
 
 
 
 
 
 
 
 
 
8a5c351
dcbfea9
 
 
 
 
 
 
8a5c351
dcbfea9
 
 
 
8a5c351
dcbfea9
 
 
 
 
 
 
8a5c351
dcbfea9
 
 
 
 
 
 
8a5c351
dcbfea9
 
 
 
 
 
 
 
 
 
8a5c351
dcbfea9
 
 
 
 
 
 
14f50a3
8a5c351
dcbfea9
 
 
 
 
 
 
8a5c351
dcbfea9
 
 
8a5c351
dcbfea9
 
 
 
 
 
 
 
 
8a5c351
dcbfea9
 
8a5c351
14f50a3
 
 
 
 
 
8a5c351
dcbfea9
 
 
 
af5b2b0
 
 
dcbfea9
af5b2b0
 
 
dcbfea9
 
 
8a5c351
dcbfea9
 
 
 
14f50a3
 
 
dcbfea9
8a5c351
dcbfea9
 
 
 
8a5c351
dcbfea9
 
 
8a5c351
66b1acd
 
 
 
 
 
 
 
 
dcbfea9
66b1acd
dcbfea9
66b1acd
dcbfea9
66b1acd
 
dcbfea9
8a5c351
dcbfea9
 
 
8a5c351
dcbfea9
 
14f50a3
 
 
8a5c351
8babf7e
 
 
 
 
 
 
dcbfea9
8babf7e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a5c351
dcbfea9
 
 
 
 
 
8a5c351
dcbfea9
 
 
8a5c351
dcbfea9
 
 
8a5c351
dcbfea9
 
 
 
 
 
 
8a5c351
dcbfea9
 
8a5c351
 
dcbfea9
 
 
 
 
 
 
14f50a3
dcbfea9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14f50a3
 
 
 
 
 
dcbfea9
 
 
 
14f50a3
 
 
 
 
dcbfea9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14f50a3
 
 
dcbfea9
 
 
 
 
 
8a5c351
dcbfea9
 
 
 
 
 
 
 
 
 
 
 
 
8a5c351
 
dcbfea9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14f50a3
8a5c351
dcbfea9
 
 
 
 
 
 
8a5c351
dcbfea9
 
 
8a5c351
dcbfea9
 
 
 
 
14f50a3
 
 
 
 
 
8a5c351
dcbfea9
 
 
 
 
 
8a5c351
dcbfea9
 
 
 
 
 
 
14f50a3
 
 
dcbfea9
 
8a5c351
dcbfea9
 
 
 
8a5c351
dcbfea9
8a5c351
dcbfea9
 
 
 
 
 
 
 
8a5c351
dcbfea9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a5c351
dcbfea9
 
 
 
 
 
8a5c351
dcbfea9
 
8a5c351
dcbfea9
 
8a5c351
dcbfea9
 
 
 
 
14f50a3
 
 
 
 
 
 
 
 
 
 
8a5c351
dcbfea9
 
 
 
 
 
 
 
 
 
 
8a5c351
dcbfea9
 
 
 
8a5c351
dcbfea9
 
 
8a5c351
dcbfea9
 
 
 
 
 
 
 
14f50a3
 
 
 
 
 
8a5c351
dcbfea9
 
 
 
 
 
8a5c351
dcbfea9
 
 
 
 
 
 
14f50a3
 
 
dcbfea9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14f50a3
 
 
dcbfea9
 
 
 
 
 
8a5c351
dcbfea9
 
 
 
 
 
 
 
 
 
 
 
 
8a5c351
 
dcbfea9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14f50a3
8a5c351
dcbfea9
 
 
 
 
 
 
8a5c351
dcbfea9
8a5c351
dcbfea9
 
 
8a5c351
dcbfea9
 
 
8a5c351
dcbfea9
 
 
 
 
 
 
 
8a5c351
dcbfea9
 
 
 
8a5c351
dcbfea9
 
 
8a5c351
dcbfea9
 
8a5c351
dcbfea9
 
 
 
 
14f50a3
 
 
 
 
 
 
dcbfea9
 
 
14f50a3
 
 
 
8a5c351
dcbfea9
 
 
 
 
 
 
 
 
 
 
 
 
8a5c351
dcbfea9
 
 
 
 
 
8a5c351
dcbfea9
 
 
 
 
 
 
8a5c351
dcbfea9
 
 
 
 
 
14f50a3
 
 
 
 
 
8a5c351
dcbfea9
 
 
 
 
 
8a5c351
dcbfea9
 
 
 
 
 
8a5c351
dcbfea9
 
 
14f50a3
 
 
dcbfea9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14f50a3
 
 
dcbfea9
 
 
 
 
 
8a5c351
dcbfea9
 
 
 
 
 
 
 
 
 
 
 
 
8a5c351
 
dcbfea9
 
 
 
 
 
8a5c351
 
dcbfea9
 
 
 
 
 
 
8a5c351
 
dcbfea9
 
 
14f50a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
import os
import uuid
import shutil
import re
import threading
from datetime import datetime, timedelta, date
from io import BytesIO
from typing import Dict, List, Optional,Any
import numpy as np
from fastapi import (
    FastAPI,
    UploadFile,
    File,
    HTTPException,
    Depends,
    Header,
    Request,
    Form,
)
from fastapi.responses import FileResponse, JSONResponse
from pydantic import BaseModel
from PIL import Image, UnidentifiedImageError
import cv2
import logging
import boto3
from gridfs import GridFS
from gridfs.errors import NoFile

from bson import ObjectId
from pymongo import MongoClient
import time

# Load environment variables from .env if present
try:
    from dotenv import load_dotenv

    load_dotenv()
except Exception:
    pass

logging.basicConfig(level=logging.INFO)
log = logging.getLogger("api")

from src.core import process_inpaint

# Directories (use writable space on HF Spaces)
BASE_DIR = os.environ.get("DATA_DIR", "/data")
if not os.path.isdir(BASE_DIR):
    # Fallback to /tmp if /data not available
    BASE_DIR = "/tmp"

UPLOAD_DIR = os.path.join(BASE_DIR, "uploads")
OUTPUT_DIR = os.path.join(BASE_DIR, "outputs")

os.makedirs(UPLOAD_DIR, exist_ok=True)
os.makedirs(OUTPUT_DIR, exist_ok=True)

SPACES_BUCKET = os.environ.get("DO_SPACES_BUCKET", "milestone")
SPACES_REGION = os.environ.get("DO_SPACES_REGION", "blr1")
SPACES_ENDPOINT = os.environ.get(
    "DO_SPACES_ENDPOINT",
    f"https://{SPACES_REGION}.digitaloceanspaces.com",
)
SPACES_KEY = os.environ.get("DO_SPACES_KEY")
SPACES_SECRET = os.environ.get("DO_SPACES_SECRET")
SPACES_ROOT_PREFIX = os.environ.get("DO_SPACES_ROOT_PREFIX", "valentine/objectremover").strip("/")
SPACES_SOURCE_PREFIX = f"{SPACES_ROOT_PREFIX}/source"
SPACES_RESULTS_PREFIX = f"{SPACES_ROOT_PREFIX}/results"

# Optional Bearer token: set env API_TOKEN to require auth; if not set, endpoints are open
ENV_TOKEN = os.environ.get("API_TOKEN")

app = FastAPI(title="Photo Object Removal API", version="1.0.0")

# In-memory stores
file_store: Dict[str, Dict[str, str]] = {}
logs: List[Dict[str, str]] = []

MONGO_URI = os.environ.get("MONGO_URI") or os.environ.get("MONGODB_URI")
mongo_client = None
mongo_db = None
mongo_logs = None
grid_fs = None

if MONGO_URI:
    try:
        mongo_client = MongoClient(MONGO_URI)
        # Try to get database from connection string first
        try:
            mongo_db = mongo_client.get_default_database()
            log.info("Using database from connection string: %s", mongo_db.name)
        except Exception as db_err:
            mongo_db = None
            log.warning("Could not extract database from connection string: %s", db_err)
        
        # Fallback to 'object_remover' if no database in connection string
        if mongo_db is None:
            mongo_db = mongo_client["object_remover"]
            log.info("Using default database: object_remover")
        
        mongo_logs = mongo_db["api_logs"]
        grid_fs = GridFS(mongo_db)
        log.info("MongoDB connection initialized successfully - Database: %s, Collection: %s", mongo_db.name, mongo_logs.name)
    except Exception as err:
        log.error("Failed to initialize MongoDB connection: %s", err, exc_info=True)
        log.warning("GridFS operations will be disabled. Set MONGO_URI or MONGODB_URI environment variable.")
else:
    log.warning("MONGO_URI not set. GridFS operations will be disabled. Upload endpoints will not work.")
# if MONGO_URI:
#     try:
#         mongo_client = MongoClient(MONGO_URI)

#         # 🔥 FORCE DB + COLLECTION
#         mongo_db = mongo_client["logs"]
#         mongo_logs = mongo_db["objectRemover"]

#         log.info("MongoDB initialized → logs/objectRemover")
#     except Exception as err:
#         log.error("Failed to initialize MongoDB connection: %s", err, exc_info=True)
#         mongo_logs = None
# else:
#     log.warning("MONGO_URI not set. Logging disabled.")
# ✅ NEW: Separate Mongo for API Logs
API_LOGS_MONGO_URI = os.environ.get("API_LOGS_MONGODB_URL")

api_logs_client = None
api_logs_db = None
api_logs_collection = None
spaces_client = None
spaces_enabled = False
spaces_counter_lock = threading.Lock()
spaces_pair_counter: Optional[int] = None

if API_LOGS_MONGO_URI:
    try:
        api_logs_client = MongoClient(API_LOGS_MONGO_URI)
        api_logs_db = api_logs_client["logs"]              # 🔥 logs database
        api_logs_collection = api_logs_db["objectRemover"] # 🔥 objectRemover collection
        log.info("API Logs Mongo initialized → logs/objectRemover")
    except Exception as e:
        log.error("Failed to initialize API Logs MongoDB: %s", e)
        api_logs_collection = None
else:
    log.warning("API_LOGS_MONGODB_URL not set. API logging disabled.")

if SPACES_KEY and SPACES_SECRET:
    try:
        spaces_client = boto3.client(
            "s3",
            region_name=SPACES_REGION,
            endpoint_url=SPACES_ENDPOINT,
            aws_access_key_id=SPACES_KEY,
            aws_secret_access_key=SPACES_SECRET,
        )
        spaces_enabled = True
        log.info(
            "DigitalOcean Spaces initialized: bucket=%s source_prefix=%s results_prefix=%s",
            SPACES_BUCKET,
            SPACES_SOURCE_PREFIX,
            SPACES_RESULTS_PREFIX,
        )
    except Exception as err:
        log.error("Failed to initialize DigitalOcean Spaces client: %s", err, exc_info=True)
        spaces_client = None
        spaces_enabled = False
else:
    log.info("DigitalOcean Spaces not configured; source/result mirroring disabled")
    
ADMIN_MONGO_URI = os.environ.get("MONGODB_ADMIN")
DEFAULT_CATEGORY_ID = "69368f722e46bd68ae188984"
admin_media_clicks = None

# Collage-maker MongoDB configuration
COLLAGE_MAKER_MONGO_URI = os.environ.get("MONGODB_COLLAGE_MAKER")
COLLAGE_MAKER_DB_NAME = os.environ.get("MONGODB_COLLAGE_MAKER_DB_NAME", "collage-maker")
COLLAGE_MAKER_ADMIN_DB_NAME = os.environ.get("MONGODB_COLLAGE_MAKER_ADMIN_DB_NAME", "adminPanel")
collage_maker_client = None
collage_maker_db = None
collage_maker_admin_db = None
collage_maker_media_clicks = None
collage_maker_categories = None

# AI-Enhancer MongoDB configuration
AI_ENHANCER_MONGO_URI = os.environ.get("MONGODB_AI_ENHANCER")
AI_ENHANCER_DB_NAME = os.environ.get("MONGODB_AI_ENHANCER_DB_NAME", "ai-enhancer")
AI_ENHANCER_ADMIN_DB_NAME = os.environ.get("MONGODB_AI_ENHANCER_ADMIN_DB_NAME", "test")
ai_enhancer_client = None
ai_enhancer_db = None
ai_enhancer_admin_db = None
ai_enhancer_media_clicks = None


def get_collage_maker_client() -> Optional[MongoClient]:
    """Get collage-maker MongoDB client."""
    global collage_maker_client
    if collage_maker_client is None and COLLAGE_MAKER_MONGO_URI:
        try:
            collage_maker_client = MongoClient(COLLAGE_MAKER_MONGO_URI)
            log.info("Collage-maker MongoDB client initialized")
        except Exception as err:
            log.error("Failed to initialize collage-maker MongoDB client: %s", err)
            collage_maker_client = None
    return collage_maker_client


def get_collage_maker_database() -> Optional[Any]:
    """Get collage-maker database instance."""
    global collage_maker_db
    client = get_collage_maker_client()
    if client is None:
        return None
    if collage_maker_db is None:
        try:
            collage_maker_db = client[COLLAGE_MAKER_DB_NAME]
            log.info("Collage-maker database initialized: %s", COLLAGE_MAKER_DB_NAME)
        except Exception as err:
            log.error("Failed to get collage-maker database: %s", err)
            collage_maker_db = None
    return collage_maker_db


def _init_collage_maker_mongo() -> None:
    """Initialize collage-maker MongoDB connections."""
    global collage_maker_admin_db, collage_maker_media_clicks, collage_maker_categories
    client = get_collage_maker_client()
    if client is None:
        log.info("Collage-maker Mongo URI not provided; collage-maker features disabled")
        return
    try:
        collage_maker_admin_db = client[COLLAGE_MAKER_ADMIN_DB_NAME]
        collage_maker_media_clicks = collage_maker_admin_db["media_clicks"]
        collage_maker_categories = collage_maker_admin_db["categories"]
        log.info(
            "Collage-maker admin initialized: db=%s, media_clicks=%s, categories=%s",
            COLLAGE_MAKER_ADMIN_DB_NAME,
            collage_maker_media_clicks.name,
            collage_maker_categories.name,
        )
    except Exception as err:
        log.error("Failed to init collage-maker admin Mongo: %s", err)
        collage_maker_admin_db = None
        collage_maker_media_clicks = None
        collage_maker_categories = None


_init_collage_maker_mongo()


def get_ai_enhancer_client() -> Optional[MongoClient]:
    """Get AI-Enhancer MongoDB client."""
    global ai_enhancer_client
    if ai_enhancer_client is None and AI_ENHANCER_MONGO_URI:
        try:
            ai_enhancer_client = MongoClient(AI_ENHANCER_MONGO_URI)
            log.info("AI-Enhancer MongoDB client initialized")
        except Exception as err:
            log.error("Failed to initialize AI-Enhancer MongoDB client: %s", err)
            ai_enhancer_client = None
    return ai_enhancer_client


def get_ai_enhancer_database() -> Optional[Any]:
    """Get AI-Enhancer database instance."""
    global ai_enhancer_db
    client = get_ai_enhancer_client()
    if client is None:
        return None
    if ai_enhancer_db is None:
        try:
            ai_enhancer_db = client[AI_ENHANCER_DB_NAME]
            log.info("AI-Enhancer database initialized: %s", AI_ENHANCER_DB_NAME)
        except Exception as err:
            log.error("Failed to get AI-Enhancer database: %s", err)
            ai_enhancer_db = None
    return ai_enhancer_db


def _init_ai_enhancer_mongo() -> None:
    """Initialize AI-Enhancer MongoDB connections."""
    global ai_enhancer_admin_db, ai_enhancer_media_clicks
    client = get_ai_enhancer_client()
    if client is None:
        log.info("AI-Enhancer Mongo URI not provided; AI-Enhancer features disabled")
        return
    try:
        ai_enhancer_admin_db = client[AI_ENHANCER_ADMIN_DB_NAME]
        ai_enhancer_media_clicks = ai_enhancer_admin_db["media_clicks"]
        log.info(
            "AI-Enhancer admin initialized: db=%s, media_clicks=%s",
            AI_ENHANCER_ADMIN_DB_NAME,
            ai_enhancer_media_clicks.name,
        )
    except Exception as err:
        log.error("Failed to init AI-Enhancer admin Mongo: %s", err)
        ai_enhancer_admin_db = None
        ai_enhancer_media_clicks = None


_init_ai_enhancer_mongo()


def get_category_id_from_collage_maker() -> Optional[str]:
    """Query category ID from collage-maker categories collection."""
    if collage_maker_categories is None:
        log.warning("Collage-maker categories collection not initialized")
        return None
    try:
        # Query the categories collection - you may need to adjust the query based on your schema
        # This assumes there's a default category or we get the first one
        category_doc = collage_maker_categories.find_one()
        if category_doc:
            category_id = str(category_doc.get("_id", ""))
            log.info("Found category ID from collage-maker: %s", category_id)
            return category_id
        else:
            log.warning("No categories found in collage-maker collection")
            return None
    except Exception as err:
        log.error("Failed to query collage-maker categories: %s", err)
        return None


def _init_admin_mongo() -> None:
    global admin_media_clicks
    if not ADMIN_MONGO_URI:
        log.info("Admin Mongo URI not provided; media click logging disabled")
        return
    try:
        admin_client = MongoClient(ADMIN_MONGO_URI)
        # get_default_database() extracts database from connection string (e.g., /adminPanel)
        try:
            admin_db = admin_client.get_default_database()
        except Exception as db_err:
            admin_db = None
            log.warning("Admin Mongo URI has no default DB; error=%s", db_err)
        if admin_db is None:
            # Fallback to provided default for this app
            admin_db = admin_client["object_remover"]
            log.warning("No database in connection string, defaulting to 'object_remover'")
        
        admin_media_clicks = admin_db["media_clicks"]
        log.info(
            "Admin media click logging initialized: db=%s collection=%s",
            admin_db.name,
            admin_media_clicks.name,
        )
        try:
            admin_media_clicks.drop_index("user_id_1_header_1_media_id_1")
            log.info("Dropped legacy index user_id_1_header_1_media_id_1")
        except Exception as idx_err:
            # Index drop failure is non-critical (often permission issue)
            if "Unauthorized" not in str(idx_err):
                log.info("Skipping legacy index drop: %s", idx_err)
    except Exception as err:
        log.error("Failed to init admin Mongo client: %s", err)
        admin_media_clicks = None


_init_admin_mongo()


def _admin_logging_status() -> Dict[str, object]:
    if admin_media_clicks is None:
        return {
            "enabled": False,
            "db": None,
            "collection": None,
        }
    return {
        "enabled": True,
        "db": admin_media_clicks.database.name,
        "collection": admin_media_clicks.name,
    }


def _save_upload_to_gridfs(upload: UploadFile, file_type: str) -> str:
    """Store an uploaded file into GridFS and return its ObjectId string."""
    if grid_fs is None:
        raise HTTPException(
            status_code=503,
            detail="MongoDB/GridFS not configured. Set MONGO_URI or MONGODB_URI environment variable."
        )
    data = upload.file.read()
    if not data:
        raise HTTPException(status_code=400, detail=f"{file_type} file is empty")
    oid = grid_fs.put(
        data,
        filename=upload.filename or f"{file_type}.bin",
        contentType=upload.content_type,
        metadata={"type": file_type},
    )
    return str(oid)


def _read_gridfs_bytes(file_id: str, expected_type: str) -> bytes:
    """Fetch raw bytes from GridFS and validate the stored type metadata."""
    if grid_fs is None:
        raise HTTPException(
            status_code=503,
            detail="MongoDB/GridFS not configured. Set MONGO_URI or MONGODB_URI environment variable."
        )
    try:
        oid = ObjectId(file_id)
    except Exception:
        raise HTTPException(status_code=404, detail=f"{expected_type}_id invalid")

    try:
        grid_out = grid_fs.get(oid)
    except NoFile:
        raise HTTPException(status_code=404, detail=f"{expected_type}_id not found")

    meta = grid_out.metadata or {}
    stored_type = meta.get("type")
    if stored_type and stored_type != expected_type:
        raise HTTPException(status_code=404, detail=f"{expected_type}_id not found")

    return grid_out.read()


def _load_rgba_image_from_gridfs(file_id: str, expected_type: str) -> Image.Image:
    """Load an image from GridFS and convert to RGBA."""
    data = _read_gridfs_bytes(file_id, expected_type)
    try:
        img = Image.open(BytesIO(data))
    except UnidentifiedImageError:
        raise HTTPException(status_code=422, detail=f"{expected_type} is not a valid image")
    return img.convert("RGBA")


def _pil_to_jpeg_bytes(img: Image.Image, quality: int = 95) -> bytes:
    buf = BytesIO()
    rgb_img = img.convert("RGB")
    rgb_img.save(buf, format="JPEG", quality=quality)
    return buf.getvalue()


def _pil_to_png_bytes(img: Image.Image) -> bytes:
    buf = BytesIO()
    img.save(buf, format="PNG", optimize=False, compress_level=1)
    return buf.getvalue()


def _extract_pair_number_from_key(key: str, prefix: str, file_label: str, ext: str) -> Optional[int]:
    normalized_prefix = prefix.strip("/")
    pattern = rf"^{re.escape(normalized_prefix)}/{file_label}_(\d+)\.{re.escape(ext)}$"
    match = re.match(pattern, key)
    if not match:
        return None
    return int(match.group(1))


def _fetch_spaces_max_pair_number() -> int:
    if not spaces_enabled or spaces_client is None:
        return 0

    max_number = 0
    for prefix, label, ext in (
        (SPACES_SOURCE_PREFIX, "source", "jpg"),
        (SPACES_RESULTS_PREFIX, "result", "png"),
    ):
        continuation_token = None
        while True:
            kwargs = {
                "Bucket": SPACES_BUCKET,
                "Prefix": f"{prefix}/",
                "MaxKeys": 1000,
            }
            if continuation_token:
                kwargs["ContinuationToken"] = continuation_token
            response = spaces_client.list_objects_v2(**kwargs)
            for item in response.get("Contents", []):
                key = item.get("Key", "")
                pair_number = _extract_pair_number_from_key(key, prefix, label, ext)
                if pair_number is not None:
                    max_number = max(max_number, pair_number)
            if not response.get("IsTruncated"):
                break
            continuation_token = response.get("NextContinuationToken")
    return max_number


def _next_spaces_pair_number() -> int:
    global spaces_pair_counter

    if not spaces_enabled or spaces_client is None:
        raise RuntimeError("DigitalOcean Spaces is not configured")

    with spaces_counter_lock:
        if spaces_pair_counter is None:
            spaces_pair_counter = _fetch_spaces_max_pair_number()
        spaces_pair_counter += 1
        return spaces_pair_counter


def _upload_bytes_to_spaces(data: bytes, key: str, content_type: str) -> None:
    if not spaces_enabled or spaces_client is None:
        return
    spaces_client.put_object(
        Bucket=SPACES_BUCKET,
        Key=key,
        Body=data,
        ContentType=content_type,
    )


def _mirror_source_result_to_spaces(
    source_image: Image.Image,
    result_image: Image.Image,
) -> Optional[Dict[str, str]]:
    if not spaces_enabled or spaces_client is None:
        return None

    pair_number = _next_spaces_pair_number()
    source_key = f"{SPACES_SOURCE_PREFIX}/source_{pair_number}.jpg"
    result_key = f"{SPACES_RESULTS_PREFIX}/result_{pair_number}.png"

    source_bytes = _pil_to_jpeg_bytes(source_image)
    result_bytes = _pil_to_png_bytes(result_image)

    _upload_bytes_to_spaces(source_bytes, source_key, "image/jpeg")
    _upload_bytes_to_spaces(result_bytes, result_key, "image/png")
    log.info(
        "Mirrored source/result to Spaces: source_key=%s result_key=%s",
        source_key,
        result_key,
    )
    return {
        "source_key": source_key,
        "result_key": result_key,
        "pair_number": str(pair_number),
    }


def _build_ai_edit_daily_count(
    existing: Optional[List[Dict[str, object]]],
    today: date,
) -> List[Dict[str, object]]:
    """
    Build / extend the ai_edit_daily_count array with the following rules:

    - Case A (no existing data): return [{date: today, count: 1}]
    - Case B (today already recorded): return list unchanged
    - Case C (gap in days): fill missing days with count=0 and append today with count=1

    Additionally, the returned list is capped to the most recent 32 entries.

    The stored "date" value is a midnight UTC (naive UTC) datetime for the given day.
    """

    def _to_date_only(value: object) -> date:
        if isinstance(value, datetime):
            return value.date()
        if isinstance(value, date):
            return value
        # Fallback: try parsing ISO string "YYYY-MM-DD" or full datetime
        try:
            text = str(value)
            if len(text) == 10:
                return datetime.strptime(text, "%Y-%m-%d").date()
            return datetime.fromisoformat(text).date()
        except Exception:
            # If parsing fails, just treat as today to avoid crashing
            return today

    # Case A: first ever use (no array yet)
    if not existing:
        return [
            {
                "date": datetime(today.year, today.month, today.day),
                "count": 1,
            }
        ]

    # Work on a shallow copy so we don't mutate original in-place
    result: List[Dict[str, object]] = list(existing)

    last_entry = result[-1] if result else None
    if not last_entry or "date" not in last_entry:
        # If structure is unexpected, re-initialize safely
        return [
            {
                "date": datetime(today.year, today.month, today.day),
                "count": 1,
            }
        ]

    last_date = _to_date_only(last_entry["date"])

    # If somehow the last stored date is in the future, do nothing to avoid corrupting history
    if last_date > today:
        return result

    # Case B: today's date already present as the last entry → unchanged
    if last_date == today:
        return result

    # Case C: there is a gap, fill missing days with count=0 and append today with count=1
    cursor = last_date + timedelta(days=1)
    while cursor < today:
        result.append(
            {
                "date": datetime(cursor.year, cursor.month, cursor.day),
                "count": 0,
            }
        )
        cursor += timedelta(days=1)

    # Finally add today's presence indicator
    result.append(
        {
            "date": datetime(today.year, today.month, today.day),
            "count": 1,
        }
    )

    # Sort by date ascending (older dates first) to guarantee stable ordering:
    # [oldest, ..., newest]
    try:
        result.sort(key=lambda entry: _to_date_only(entry.get("date")))
    except Exception:
        # If anything goes wrong during sort, fall back to current ordering
        pass

    # Enforce 32-entry limit (keep the most recent 32 days)
    if len(result) > 32:
        result = result[-32:]

    return result

def bearer_auth(authorization: Optional[str] = Header(default=None)) -> None:
    if not ENV_TOKEN:
        return
    if authorization is None or not authorization.lower().startswith("bearer "):
        raise HTTPException(status_code=401, detail="Unauthorized")
    token = authorization.split(" ", 1)[1]
    if token != ENV_TOKEN:
        raise HTTPException(status_code=403, detail="Forbidden")


class InpaintRequest(BaseModel):
    image_id: str
    mask_id: str
    invert_mask: bool = True  # True => selected/painted area is removed
    passthrough: bool = False  # If True, return the original image unchanged
    prompt: Optional[str] = None  # Optional: describe what to remove
    user_id: Optional[str] = None
    category_id: Optional[str] = None
    appname: Optional[str] = None  # Optional: app name (e.g., "collage-maker")


class SimpleRemoveRequest(BaseModel):
    image_id: str  # Image with pink/magenta segments to remove


def _coerce_object_id(value: Optional[str]) -> ObjectId:
    if value is None:
        return ObjectId()
    value_str = str(value).strip()
    if re.fullmatch(r"[0-9a-fA-F]{24}", value_str):
        return ObjectId(value_str)
    if value_str.isdigit():
        hex_str = format(int(value_str), "x")
        if len(hex_str) > 24:
            hex_str = hex_str[-24:]
        hex_str = hex_str.rjust(24, "0")
        return ObjectId(hex_str)
    return ObjectId()


def _coerce_category_id(category_id: Optional[str]) -> ObjectId:
    raw = category_id or DEFAULT_CATEGORY_ID
    raw_str = str(raw).strip()
    if re.fullmatch(r"[0-9a-fA-F]{24}", raw_str):
        return ObjectId(raw_str)
    return _coerce_object_id(raw_str)


def log_media_click(user_id: Optional[str], category_id: Optional[str], appname: Optional[str] = None) -> None:
    """Log to admin media_clicks collection only if user_id is provided.
    
    If appname='collage-maker', logs to collage-maker MongoDB instead of regular admin MongoDB.
    If appname='AI-Enhancer' (case-insensitive), logs to AI-Enhancer MongoDB.
    """
    # Determine which media_clicks collection to use
    target_media_clicks = None
    appname_lower = appname.lower() if appname else None
    
    if appname_lower == "collage-maker":
        target_media_clicks = collage_maker_media_clicks
        if target_media_clicks is None:
            log.warning("Collage-maker media_clicks not initialized, skipping log")
            return
    elif appname_lower == "ai-enhancer":
        target_media_clicks = ai_enhancer_media_clicks
        if target_media_clicks is None:
            log.warning("AI-Enhancer media_clicks not initialized, skipping log")
            return
    else:
        target_media_clicks = admin_media_clicks
        if target_media_clicks is None:
            return
    
    # Only log if user_id is provided (not None/empty)
    if not user_id or not user_id.strip():
        return
    try:
        user_obj = _coerce_object_id(user_id)
        category_obj = _coerce_category_id(category_id)
        now = datetime.utcnow()
        today = now.date()

        doc = target_media_clicks.find_one({"userId": user_obj})
        if doc:
            existing_daily = doc.get("ai_edit_daily_count")
            updated_daily = _build_ai_edit_daily_count(existing_daily, today)
            categories = doc.get("categories") or []
            if any(cat.get("categoryId") == category_obj for cat in categories):
                # Category exists: increment click_count and ai_edit_complete, update dates
                target_media_clicks.update_one(
                    {"_id": doc["_id"], "categories.categoryId": category_obj},
                    {
                        "$inc": {
                            "categories.$.click_count": 1,
                            "ai_edit_complete": 1,  # $inc handles missing fields (backward compatible)
                        },
                        "$set": {
                            "categories.$.lastClickedAt": now,
                            "updatedAt": now,
                            "ai_edit_last_date": now,
                            "ai_edit_daily_count": updated_daily,
                        },
                    },
                )
            else:
                # New category to existing document: push category, increment ai_edit_complete
                target_media_clicks.update_one(
                    {"_id": doc["_id"]},
                    {
                        "$push": {
                            "categories": {
                                "categoryId": category_obj,
                                "click_count": 1,
                                "lastClickedAt": now,
                            }
                        },
                        "$inc": {"ai_edit_complete": 1},  # $inc handles missing fields
                        "$set": {
                            "updatedAt": now,
                            "ai_edit_last_date": now,
                            "ai_edit_daily_count": updated_daily,
                        },
                    },
                )
        else:
            # New user: create document with default ai_edit_complete=0, then increment to 1
            daily_for_new = _build_ai_edit_daily_count(None, today)
            target_media_clicks.update_one(
                {"userId": user_obj},
                {
                    "$setOnInsert": {
                        "userId": user_obj,
                        "categories": [
                            {
                                "categoryId": category_obj,
                                "click_count": 1,
                                "lastClickedAt": now,
                            }
                        ],
                        "createdAt": now,
                        "ai_edit_daily_count": daily_for_new,
                    },
                    "$inc": {"ai_edit_complete": 1},  # Increment to 1 on first use
                    "$set": {
                        "updatedAt": now,
                        "ai_edit_last_date": now,
                    },
                },
                upsert=True,
            )
    except Exception as err:
        err_str = str(err)
        appname_lower = appname.lower() if appname else None
        if appname_lower == "collage-maker":
            target_name = "collage-maker"
        elif appname_lower == "ai-enhancer":
            target_name = "AI-Enhancer"
        else:
            target_name = "admin"
        if "Unauthorized" in err_str or "not authorized" in err_str.lower():
            log.warning(
                "%s media click logging failed (permissions): user lacks read/write on db=%s collection=%s. "
                "Check MongoDB user permissions.",
                target_name,
                target_media_clicks.database.name,
                target_media_clicks.name,
            )
        else:
            log.warning("%s media click logging failed: %s", target_name, err)


@app.get("/")
def root() -> Dict[str, Any]:
    return {
        "success": True,
        "message": "Object Remover API",
        "data": {
            "version": "1.0.0",
            "product_name": "Beauty Camera - GlowCam AI Studio",
            "released_by": "LogicGo Infotech"
        }
    }



@app.get("/health")
def health() -> Dict[str, str]:
    return {"status": "healthy"}


@app.get("/logging-status")
def logging_status(_: None = Depends(bearer_auth)) -> Dict[str, object]:
    """Helper endpoint to verify admin media logging wiring (no secrets exposed)."""
    return _admin_logging_status()


@app.get("/mongo-status")
def mongo_status(_: None = Depends(bearer_auth)) -> Dict[str, object]:
    """Check MongoDB connection status and verify data storage."""
    status = {
        "mongo_configured": MONGO_URI is not None,
        "mongo_connected": mongo_client is not None,
        "database": mongo_db.name if mongo_db else None,
        "collection": mongo_logs.name if mongo_logs else None,
        "admin_logging": _admin_logging_status(),
    }
    
    # Try to count documents in api_logs collection
    if mongo_logs is not None:
        try:
            count = mongo_logs.count_documents({})
            status["api_logs_count"] = count
            # Get latest 5 documents
            latest_docs = list(mongo_logs.find().sort("timestamp", -1).limit(5))
            status["recent_logs"] = []
            for doc in latest_docs:
                doc_dict = {
                    "_id": str(doc.get("_id")),
                    "output_id": doc.get("output_id"),
                    "status": doc.get("status"),
                    "timestamp": doc.get("timestamp").isoformat() if isinstance(doc.get("timestamp"), datetime) else str(doc.get("timestamp")),
                }
                if "input_image_id" in doc:
                    doc_dict["input_image_id"] = doc.get("input_image_id")
                if "input_mask_id" in doc:
                    doc_dict["input_mask_id"] = doc.get("input_mask_id")
                if "error" in doc:
                    doc_dict["error"] = doc.get("error")
                status["recent_logs"].append(doc_dict)
            
            # Get latest document for backward compatibility
            if latest_docs:
                latest = latest_docs[0]
                status["latest_log"] = {
                    "_id": str(latest.get("_id")),
                    "output_id": latest.get("output_id"),
                    "status": latest.get("status"),
                    "timestamp": latest.get("timestamp").isoformat() if isinstance(latest.get("timestamp"), datetime) else str(latest.get("timestamp")),
                }
        except Exception as err:
            status["api_logs_error"] = str(err)
            log.error("Error querying MongoDB: %s", err, exc_info=True)
    
    return status


@app.post("/upload-image")
def upload_image(image: UploadFile = File(...), _: None = Depends(bearer_auth)) -> Dict[str, str]:
    file_id = _save_upload_to_gridfs(image, "image")
    logs.append({"id": file_id, "filename": image.filename, "type": "image", "timestamp": datetime.utcnow().isoformat()})
    return {"id": file_id, "filename": image.filename}


@app.post("/upload-mask")
def upload_mask(mask: UploadFile = File(...), _: None = Depends(bearer_auth)) -> Dict[str, str]:
    file_id = _save_upload_to_gridfs(mask, "mask")
    logs.append({"id": file_id, "filename": mask.filename, "type": "mask", "timestamp": datetime.utcnow().isoformat()})
    return {"id": file_id, "filename": mask.filename}


def _compress_image(image_path: str, output_path: str, quality: int = 85) -> None:
    """
    Compress an image to reduce file size.
    Converts to JPEG format with specified quality to achieve smaller file size.
    """
    img = Image.open(image_path)
    # Convert RGBA to RGB if needed (JPEG doesn't support alpha)
    if img.mode == "RGBA":
        rgb_img = Image.new("RGB", img.size, (255, 255, 255))
        rgb_img.paste(img, mask=img.split()[3])  # Use alpha channel as mask
        img = rgb_img
    elif img.mode != "RGB":
        img = img.convert("RGB")
    
    # Save as JPEG with quality setting for compression
    img.save(output_path, "JPEG", quality=quality, optimize=True)


def _load_rgba_mask_from_image(img: Image.Image) -> np.ndarray:
    """
    Convert mask image to RGBA format (black/white mask).
    Standard convention: white (255) = area to remove, black (0) = area to keep
    Returns RGBA with white in RGB channels where removal is needed, alpha=255
    """
    if img.mode != "RGBA":
        # For RGB/Grayscale masks: white (value>128) = remove, black (value<=128) = keep
        gray = img.convert("L")
        arr = np.array(gray)
        # Create proper black/white mask: white pixels (>128) = remove, black (<=128) = keep
        mask_bw = np.where(arr > 128, 255, 0).astype(np.uint8)
        
        rgba = np.zeros((img.height, img.width, 4), dtype=np.uint8)
        rgba[:, :, 0] = mask_bw  # R
        rgba[:, :, 1] = mask_bw  # G
        rgba[:, :, 2] = mask_bw  # B
        rgba[:, :, 3] = 255  # Fully opaque
        log.info(f"Loaded {img.mode} mask: {int((mask_bw > 0).sum())} white pixels (to remove)")
        return rgba
    
    # For RGBA: check if alpha channel is meaningful
    arr = np.array(img)
    alpha = arr[:, :, 3]
    rgb = arr[:, :, :3]
    
    # If alpha is mostly opaque everywhere (mean > 200), treat RGB channels as mask values
    if alpha.mean() > 200:
        # Use RGB to determine mask: white/bright in RGB = remove
        gray = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY)
        # Also detect magenta specifically
        magenta = np.all(rgb == [255, 0, 255], axis=2).astype(np.uint8) * 255
        mask_bw = np.maximum(np.where(gray > 128, 255, 0).astype(np.uint8), magenta)
        
        rgba = arr.copy()
        rgba[:, :, 0] = mask_bw  # R
        rgba[:, :, 1] = mask_bw  # G
        rgba[:, :, 2] = mask_bw  # B
        rgba[:, :, 3] = 255  # Fully opaque
        log.info(f"Loaded RGBA mask (RGB-based): {int((mask_bw > 0).sum())} white pixels (to remove)")
        return rgba
    
    # Alpha channel encodes the mask - convert to RGB-based
    # Transparent areas (alpha < 128) = remove, Opaque areas = keep
    mask_bw = np.where(alpha < 128, 255, 0).astype(np.uint8)
    rgba = arr.copy()
    rgba[:, :, 0] = mask_bw
    rgba[:, :, 1] = mask_bw
    rgba[:, :, 2] = mask_bw
    rgba[:, :, 3] = 255
    log.info(f"Loaded RGBA mask (alpha-based): {int((mask_bw > 0).sum())} white pixels (to remove)")
    return rgba

@app.post("/inpaint")
def inpaint(req: InpaintRequest, request: Request, _: None = Depends(bearer_auth)) -> Dict[str, str]:
    start_time = time.time()
    status = "success"
    error_msg = None
    output_name = None
    compressed_url = None
    spaces_info = None

    try:
        # Handle appname="collage-maker": get category_id from collage-maker if not provided
        category_id = req.category_id
        if req.appname == "collage-maker" and not category_id:
            category_id = get_category_id_from_collage_maker()
            if category_id:
                log.info("Using category_id from collage-maker: %s", category_id)

        img_rgba = _load_rgba_image_from_gridfs(req.image_id, "image")
        mask_img = _load_rgba_image_from_gridfs(req.mask_id, "mask")
        mask_rgba = _load_rgba_mask_from_image(mask_img)

        if req.passthrough:
            result = np.array(img_rgba.convert("RGB"))
        else:
            result = process_inpaint(
                np.array(img_rgba), 
                mask_rgba, 
                invert_mask=req.invert_mask,
                prompt=req.prompt,
            )

        output_name = f"output_{uuid.uuid4().hex}.png"
        output_path = os.path.join(OUTPUT_DIR, output_name)

        result_image = Image.fromarray(result)
        result_image.save(output_path, "PNG", optimize=False, compress_level=1)
        try:
            spaces_info = _mirror_source_result_to_spaces(img_rgba, result_image)
        except Exception as spaces_err:
            log.error("Failed to mirror /inpaint images to DigitalOcean Spaces: %s", spaces_err, exc_info=True)

        # Create compressed version
        compressed_name = f"compressed_{output_name.replace('.png', '.jpg')}"
        compressed_path = os.path.join(OUTPUT_DIR, compressed_name)
        try:
            # _compress_image(output_path, compressed_path, quality=85)
            # # compressed_url = str(request.url_for("download_file", filename=compressed_name))
            # compressed_url = str(request.url_for("download_file", filename=compressed_name).replace("http://", "https://"))
            _compress_image(output_path, compressed_path, quality=85)
            compressed_url = str(
                request.url_for("download_file", filename=compressed_name)
            ).replace("http://", "https://")
        except Exception as compress_err:
            log.warning("Failed to create compressed image: %s", compress_err)
            compressed_url = None

        log_media_click(req.user_id, category_id, req.appname)
        response = {"result": output_name}
        if compressed_url:
            response["Compressed_Image_URL"] = compressed_url
        if spaces_info:
            response["source_space_key"] = spaces_info["source_key"]
            response["result_space_key"] = spaces_info["result_key"]
        return response

    except Exception as e:
        status = "fail"
        error_msg = str(e)
        raise

    finally:
        end_time = time.time()
        response_time_ms = (end_time - start_time) * 1000

        # log_doc = {
        #     "input_image_id": req.image_id,
        #     "input_mask_id": req.mask_id,
        #     "output_id": output_name,
        #     "status": status,
        #     "timestamp": datetime.utcnow(),
        #     "ts": int(time.time()),
        #     "response_time_ms": response_time_ms
        # }
        log_doc = {
            "endpoint": "/inpaint",
            "status": status,
            "response_time_ms": float(response_time_ms),
            "timestamp": datetime.utcnow(),
            "appname": req.appname if req.appname else "None",
            "error": error_msg
        }

        # Store appname in api_logs if provided
        if req.appname:
            log_doc["appname"] = req.appname

        if error_msg:
            log_doc["error"] = error_msg
        if spaces_info:
            log_doc["source_space_key"] = spaces_info["source_key"]
            log_doc["result_space_key"] = spaces_info["result_key"]

        # if mongo_logs is not None:
        #     try:
        #         log.info("Inserting log to MongoDB - Database: %s, Collection: %s", mongo_logs.database.name, mongo_logs.name)
        #         log.debug("Log document: %s", log_doc)
        #         result = mongo_logs.insert_one(log_doc)
        #         log.info("Mongo log inserted successfully: _id=%s, output_id=%s, status=%s, db=%s, collection=%s", 
        #                 result.inserted_id, output_name, status, mongo_logs.database.name, mongo_logs.name)
                
        #         # Verify the insert by reading it back
        #         try:
        #             verify_doc = mongo_logs.find_one({"_id": result.inserted_id})
        #             if verify_doc:
        #                 log.info("Verified: Document exists in MongoDB after insert")
        #             else:
        #                 log.error("WARNING: Document not found after insert! _id=%s", result.inserted_id)
        #         except Exception as verify_err:
        #             log.warning("Could not verify insert: %s", verify_err)
        #     except Exception as mongo_err:
        #         log.error("Mongo log insert failed: %s, log_doc=%s", mongo_err, log_doc, exc_info=True)
        # else:
        #     log.warning("MongoDB not configured, skipping log insert")
        if api_logs_collection is not None:
            try:
                api_logs_collection.insert_one(log_doc)
                log.info("API log inserted into logs/objectRemover")
            except Exception as e:
                log.error("Failed to insert API log: %s", e)

# @app.post("/inpaint")
# def inpaint(req: InpaintRequest, _: None = Depends(bearer_auth)) -> Dict[str, str]:
#     if req.image_id not in file_store or file_store[req.image_id]["type"] != "image":
#         raise HTTPException(status_code=404, detail="image_id not found")
#     if req.mask_id not in file_store or file_store[req.mask_id]["type"] != "mask":
#         raise HTTPException(status_code=404, detail="mask_id not found")

#     img_rgba = _load_rgba_image(file_store[req.image_id]["path"])
#     mask_img = Image.open(file_store[req.mask_id]["path"])  # may be RGB/gray/RGBA
#     mask_rgba = _load_rgba_mask_from_image(mask_img)

#     # Debug: check mask before processing
#     white_pixels = int((mask_rgba[:,:,0] > 128).sum())
#     log.info(f"Inpaint request: mask has {white_pixels} white pixels, invert_mask={req.invert_mask}")

#     if req.passthrough:
#         result = np.array(img_rgba.convert("RGB"))
#     else:
#         result = process_inpaint(np.array(img_rgba), mask_rgba, invert_mask=req.invert_mask)
#     result_name = f"output_{uuid.uuid4().hex}.png"
#     result_path = os.path.join(OUTPUT_DIR, result_name)
#     Image.fromarray(result).save(result_path, "PNG", optimize=False, compress_level=1)

#     logs.append({"result": result_name, "timestamp": datetime.utcnow().isoformat()})
#     return {"result": result_name}


@app.post("/inpaint-url")
def inpaint_url(req: InpaintRequest, request: Request, _: None = Depends(bearer_auth)) -> Dict[str, str]:
    """Same as /inpaint but returns a JSON with a public download URL instead of image bytes."""
    start_time = time.time()
    status = "success"
    error_msg = None
    result_name = None
    spaces_info = None

    try:
        # Handle appname="collage-maker": get category_id from collage-maker if not provided
        category_id = req.category_id
        if req.appname == "collage-maker" and not category_id:
            category_id = get_category_id_from_collage_maker()
            if category_id:
                log.info("Using category_id from collage-maker: %s", category_id)

        img_rgba = _load_rgba_image_from_gridfs(req.image_id, "image")
        mask_img = _load_rgba_image_from_gridfs(req.mask_id, "mask")  # may be RGB/gray/RGBA
        mask_rgba = _load_rgba_mask_from_image(mask_img)

        if req.passthrough:
            result = np.array(img_rgba.convert("RGB"))
        else:
            result = process_inpaint(
                np.array(img_rgba),
                mask_rgba,
                invert_mask=req.invert_mask,
                prompt=req.prompt,
            )
        result_name = f"output_{uuid.uuid4().hex}.png"
        result_path = os.path.join(OUTPUT_DIR, result_name)
        result_image = Image.fromarray(result)
        result_image.save(result_path, "PNG", optimize=False, compress_level=1)
        try:
            spaces_info = _mirror_source_result_to_spaces(img_rgba, result_image)
        except Exception as spaces_err:
            log.error("Failed to mirror /inpaint-url images to DigitalOcean Spaces: %s", spaces_err, exc_info=True)

        url = str(request.url_for("download_file", filename=result_name))
        logs.append({"result": result_name, "url": url, "timestamp": datetime.utcnow().isoformat()})
        log_media_click(req.user_id, category_id, req.appname)
        response = {"result": result_name, "url": url}
        if spaces_info:
            response["source_space_key"] = spaces_info["source_key"]
            response["result_space_key"] = spaces_info["result_key"]
        return response
    except Exception as e:
        status = "fail"
        error_msg = str(e)
        raise
    finally:
        # Always log to regular MongoDB (mandatory)
        end_time = time.time()
        response_time_ms = (end_time - start_time) * 1000
        log_doc = {
            "input_image_id": req.image_id,
            "input_mask_id": req.mask_id,
            "output_id": result_name,
            "status": status,
            "timestamp": datetime.utcnow(),
            "ts": int(time.time()),
            "response_time_ms": response_time_ms,
        }
        # Store appname in api_logs if provided
        if req.appname:
            log_doc["appname"] = req.appname
        if error_msg:
            log_doc["error"] = error_msg
        if spaces_info:
            log_doc["source_space_key"] = spaces_info["source_key"]
            log_doc["result_space_key"] = spaces_info["result_key"]
        if mongo_logs is not None:
            try:
                log.info("Inserting log to MongoDB - Database: %s, Collection: %s", mongo_logs.database.name, mongo_logs.name)
                result = mongo_logs.insert_one(log_doc)
                log.info("Mongo log inserted successfully: _id=%s, output_id=%s, status=%s, db=%s, collection=%s", 
                        result.inserted_id, output_name, status, mongo_logs.database.name, mongo_logs.name)
                
                # Verify the insert by reading it back
                try:
                    verify_doc = mongo_logs.find_one({"_id": result.inserted_id})
                    if verify_doc:
                        log.info("Verified: Document exists in MongoDB after insert")
                    else:
                        log.error("WARNING: Document not found after insert! _id=%s", result.inserted_id)
                except Exception as verify_err:
                    log.warning("Could not verify insert: %s", verify_err)
            except Exception as mongo_err:
                log.error("Mongo log insert failed: %s, log_doc=%s", mongo_err, log_doc, exc_info=True)
        else:
            log.warning("MongoDB not configured, skipping log insert")


@app.post("/inpaint-multipart")
def inpaint_multipart(
    image: UploadFile = File(...),
    mask: UploadFile = File(...),
    request: Request = None,
    invert_mask: bool = True,
    mask_is_painted: bool = False,  # if True, mask file is the painted-on image (e.g., black strokes on original)
    passthrough: bool = False,
    prompt: Optional[str] = Form(None),
    user_id: Optional[str] = Form(None),
    category_id: Optional[str] = Form(None),
    appname: Optional[str] = Form(None),
    _: None = Depends(bearer_auth),
) -> Dict[str, str]:
    start_time = time.time()
    status = "success"
    error_msg = None
    result_name = None
    spaces_info = None
    
    try:
        # Handle appname="collage-maker": get category_id from collage-maker if not provided
        final_category_id = category_id
        if appname == "collage-maker" and not final_category_id:
            final_category_id = get_category_id_from_collage_maker()
            if final_category_id:
                log.info("Using category_id from collage-maker: %s", final_category_id)
        
        # Load in-memory
        img = Image.open(image.file).convert("RGBA")
        m = Image.open(mask.file).convert("RGBA")

        if passthrough:
            # Just echo the input image, ignore mask
            result = np.array(img.convert("RGB"))
            result_name = f"output_{uuid.uuid4().hex}.png"
            result_path = os.path.join(OUTPUT_DIR, result_name)
            result_image = Image.fromarray(result)
            result_image.save(result_path, "PNG", optimize=False, compress_level=1)
            try:
                spaces_info = _mirror_source_result_to_spaces(img, result_image)
            except Exception as spaces_err:
                log.error("Failed to mirror /inpaint-multipart passthrough images to DigitalOcean Spaces: %s", spaces_err, exc_info=True)

            url: Optional[str] = None
            try:
                if request is not None:
                    url = str(request.url_for("download_file", filename=result_name))
            except Exception:
                url = None

            entry: Dict[str, str] = {"result": result_name, "timestamp": datetime.utcnow().isoformat()}
            if url:
                entry["url"] = url
            logs.append(entry)
            resp: Dict[str, str] = {"result": result_name}
            if url:
                resp["url"] = url
            if spaces_info:
                resp["source_space_key"] = spaces_info["source_key"]
                resp["result_space_key"] = spaces_info["result_key"]
            log_media_click(user_id, final_category_id, appname)
            return resp

        if mask_is_painted:
            # Auto-detect pink/magenta paint and convert to black/white mask
            # White pixels = areas to remove, Black pixels = areas to keep
            log.info("Auto-detecting pink/magenta paint from uploaded image...")
            
            m_rgb = cv2.cvtColor(np.array(m), cv2.COLOR_RGBA2RGB)
            
            # Detect pink/magenta using fixed RGB bounds (same as /remove-pink)
            lower = np.array([150, 0, 100], dtype=np.uint8)
            upper = np.array([255, 120, 255], dtype=np.uint8)
            magenta_detected = (
                (m_rgb[:, :, 0] >= lower[0]) & (m_rgb[:, :, 0] <= upper[0]) &
                (m_rgb[:, :, 1] >= lower[1]) & (m_rgb[:, :, 1] <= upper[1]) &
                (m_rgb[:, :, 2] >= lower[2]) & (m_rgb[:, :, 2] <= upper[2])
            ).astype(np.uint8) * 255
            
            # Method 2: Also check if original image was provided to find differences
            if img is not None:
                img_rgb = cv2.cvtColor(np.array(img), cv2.COLOR_RGBA2RGB)
                if img_rgb.shape == m_rgb.shape:
                    diff = cv2.absdiff(img_rgb, m_rgb)
                    gray_diff = cv2.cvtColor(diff, cv2.COLOR_RGB2GRAY)
                    # Any significant difference (>50) could be paint
                    diff_mask = (gray_diff > 50).astype(np.uint8) * 255
                    # Combine with magenta detection
                    binmask = cv2.bitwise_or(magenta_detected, diff_mask)
                else:
                    binmask = magenta_detected
            else:
                # No original image provided, use magenta detection only
                binmask = magenta_detected
            
            # Clean up the mask: remove noise and fill small holes
            kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
            # Close small gaps in the mask
            binmask = cv2.morphologyEx(binmask, cv2.MORPH_CLOSE, kernel, iterations=2)
            # Remove small noise
            binmask = cv2.morphologyEx(binmask, cv2.MORPH_OPEN, kernel, iterations=1)
            
            nonzero = int((binmask > 0).sum())
            log.info("Pink/magenta paint detected: %d pixels marked for removal (white)", nonzero)
            
            # If very few pixels detected, assume the user may already be providing a BW mask
            # and proceed without forcing strict detection
            
            if nonzero < 50:
                log.error("CRITICAL: Could not detect pink/magenta paint! Returning original image.")
                result = np.array(img.convert("RGB")) if img else np.array(m.convert("RGB"))
                result_name = f"output_{uuid.uuid4().hex}.png"
                result_path = os.path.join(OUTPUT_DIR, result_name)
                result_image = Image.fromarray(result)
                result_image.save(result_path, "PNG", optimize=False, compress_level=1)
                try:
                    spaces_info = _mirror_source_result_to_spaces(img if img else m, result_image)
                except Exception as spaces_err:
                    log.error("Failed to mirror /inpaint-multipart fallback images to DigitalOcean Spaces: %s", spaces_err, exc_info=True)
                response = {"result": result_name, "error": "pink/magenta paint detection failed - very few pixels detected"}
                if spaces_info:
                    response["source_space_key"] = spaces_info["source_key"]
                    response["result_space_key"] = spaces_info["result_key"]
                return response
            
            # Create binary mask: Pink pixels → white (255), Everything else → black (0)
            # Encode in RGBA format for process_inpaint
            # process_inpaint does: mask = 255 - mask[:,:,3]
            # So: alpha=0 (transparent/pink) → becomes 255 (white/remove)
            #     alpha=255 (opaque/keep) → becomes 0 (black/keep)
            mask_rgba = np.zeros((binmask.shape[0], binmask.shape[1], 4), dtype=np.uint8)
            mask_rgba[:, :, 0] = binmask  # R: white where pink (for visualization)
            mask_rgba[:, :, 1] = binmask  # G: white where pink
            mask_rgba[:, :, 2] = binmask  # B: white where pink
            # Alpha: invert so pink areas get alpha=0 → will become white after 255-alpha
            mask_rgba[:, :, 3] = 255 - binmask
            
            log.info("Successfully created binary mask: %d pink pixels → white (255), %d pixels → black (0)",
                     nonzero, binmask.shape[0] * binmask.shape[1] - nonzero)
        else:
            mask_rgba = _load_rgba_mask_from_image(m)

        # When mask_is_painted=true, we encode pink as alpha=0, so process_inpaint's default invert_mask=True works correctly
        actual_invert = invert_mask  # Use default True for painted masks
        log.info("Using invert_mask=%s (mask_is_painted=%s)", actual_invert, mask_is_painted)
        
        result = process_inpaint(
            np.array(img),
            mask_rgba,
            invert_mask=actual_invert,
            prompt=prompt,
        )
        result_name = f"output_{uuid.uuid4().hex}.png"
        result_path = os.path.join(OUTPUT_DIR, result_name)
        result_image = Image.fromarray(result)
        result_image.save(result_path, "PNG", optimize=False, compress_level=1)
        try:
            spaces_info = _mirror_source_result_to_spaces(img, result_image)
        except Exception as spaces_err:
            log.error("Failed to mirror /inpaint-multipart images to DigitalOcean Spaces: %s", spaces_err, exc_info=True)

        url: Optional[str] = None
        try:
            if request is not None:
                url = str(request.url_for("download_file", filename=result_name))
        except Exception:
            url = None

        entry: Dict[str, str] = {"result": result_name, "timestamp": datetime.utcnow().isoformat()}
        if url:
            entry["url"] = url
        logs.append(entry)
        resp: Dict[str, str] = {"result": result_name}
        if url:
            resp["url"] = url
        if spaces_info:
            resp["source_space_key"] = spaces_info["source_key"]
            resp["result_space_key"] = spaces_info["result_key"]
        log_media_click(user_id, final_category_id, appname)
        return resp
    except Exception as e:
        status = "fail"
        error_msg = str(e)
        raise
    finally:
        # Always log to regular MongoDB (mandatory)
        end_time = time.time()
        response_time_ms = (end_time - start_time) * 1000
        log_doc = {
            "endpoint": "inpaint-multipart",
            "output_id": result_name,
            "status": status,
            "timestamp": datetime.utcnow(),
            "ts": int(time.time()),
            "response_time_ms": response_time_ms,
        }
        # Store appname in api_logs if provided
        if appname:
            log_doc["appname"] = appname
        if error_msg:
            log_doc["error"] = error_msg
        if spaces_info:
            log_doc["source_space_key"] = spaces_info["source_key"]
            log_doc["result_space_key"] = spaces_info["result_key"]
        if mongo_logs is not None:
            try:
                log.info("Inserting log to MongoDB - Database: %s, Collection: %s", mongo_logs.database.name, mongo_logs.name)
                result = mongo_logs.insert_one(log_doc)
                log.info("Mongo log inserted successfully: _id=%s, output_id=%s, status=%s, db=%s, collection=%s", 
                        result.inserted_id, output_name, status, mongo_logs.database.name, mongo_logs.name)
                
                # Verify the insert by reading it back
                try:
                    verify_doc = mongo_logs.find_one({"_id": result.inserted_id})
                    if verify_doc:
                        log.info("Verified: Document exists in MongoDB after insert")
                    else:
                        log.error("WARNING: Document not found after insert! _id=%s", result.inserted_id)
                except Exception as verify_err:
                    log.warning("Could not verify insert: %s", verify_err)
            except Exception as mongo_err:
                log.error("Mongo log insert failed: %s, log_doc=%s", mongo_err, log_doc, exc_info=True)
        else:
            log.warning("MongoDB not configured, skipping log insert")


@app.post("/remove-pink")
def remove_pink_segments(
    image: UploadFile = File(...),
    request: Request = None,
    user_id: Optional[str] = Form(None),
    category_id: Optional[str] = Form(None),
    appname: Optional[str] = Form(None),
    _: None = Depends(bearer_auth),
) -> Dict[str, str]:
    """
    Simple endpoint: upload an image with pink/magenta segments to remove.
    - Pink/Magenta segments → automatically removed (white in mask)
    - Everything else → automatically kept (black in mask)
    Just paint pink/magenta on areas you want to remove, upload the image, and it works!
    """
    start_time = time.time()
    status = "success"
    error_msg = None
    result_name = None
    spaces_info = None
    
    try:
        # Handle appname="collage-maker": get category_id from collage-maker if not provided
        final_category_id = category_id
        if appname == "collage-maker" and not final_category_id:
            final_category_id = get_category_id_from_collage_maker()
            if final_category_id:
                log.info("Using category_id from collage-maker: %s", final_category_id)
        
        log.info(f"Simple remove-pink: processing image {image.filename}")
        
        # Load the image (with pink paint on it)
        img = Image.open(image.file).convert("RGBA")
        img_rgb = cv2.cvtColor(np.array(img), cv2.COLOR_RGBA2RGB)
        
        # Auto-detect pink/magenta segments to remove
        # Pink/Magenta → white in mask (remove)
        # Everything else (natural image colors, including dark areas) → black in mask (keep)
        
        # Detect pink/magenta using fixed RGB bounds per requested logic
        lower = np.array([150, 0, 100], dtype=np.uint8)
        upper = np.array([255, 120, 255], dtype=np.uint8)
        binmask = (
            (img_rgb[:, :, 0] >= lower[0]) & (img_rgb[:, :, 0] <= upper[0]) &
            (img_rgb[:, :, 1] >= lower[1]) & (img_rgb[:, :, 1] <= upper[1]) &
            (img_rgb[:, :, 2] >= lower[2]) & (img_rgb[:, :, 2] <= upper[2])
        ).astype(np.uint8) * 255
        
        # Clean up the pink mask
        kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
        binmask = cv2.morphologyEx(binmask, cv2.MORPH_CLOSE, kernel, iterations=2)
        binmask = cv2.morphologyEx(binmask, cv2.MORPH_OPEN, kernel, iterations=1)
        
        nonzero = int((binmask > 0).sum())
        total_pixels = binmask.shape[0] * binmask.shape[1]
        log.info(f"Detected {nonzero} pink pixels ({100*nonzero/total_pixels:.2f}% of image) to remove")
        
        # Debug: log bounds used
        log.info("Pink detection bounds used: lower=[150,0,100], upper=[255,120,255]")
        
        if nonzero < 50:
            log.error("No pink segments detected! Returning original image.")
            result = np.array(img.convert("RGB"))
            result_name = f"output_{uuid.uuid4().hex}.png"
            result_path = os.path.join(OUTPUT_DIR, result_name)
            result_image = Image.fromarray(result)
            result_image.save(result_path, "PNG", optimize=False, compress_level=1)
            try:
                spaces_info = _mirror_source_result_to_spaces(img, result_image)
            except Exception as spaces_err:
                log.error("Failed to mirror /remove-pink fallback images to DigitalOcean Spaces: %s", spaces_err, exc_info=True)
            response = {
                "result": result_name,
                "error": "No pink/magenta segments detected. Please paint areas to remove with magenta/pink color (RGB 255,0,255)."
            }
            if spaces_info:
                response["source_space_key"] = spaces_info["source_key"]
                response["result_space_key"] = spaces_info["result_key"]
            return response
        
        # Create binary mask: Pink pixels → white (255), Everything else → black (0)
        # Encode in RGBA format that process_inpaint expects
        # process_inpaint does: mask = 255 - mask[:,:,3]
        # So: alpha=0 (transparent/pink) → becomes 255 (white/remove)
        #     alpha=255 (opaque/keep) → becomes 0 (black/keep)
        mask_rgba = np.zeros((binmask.shape[0], binmask.shape[1], 4), dtype=np.uint8)
        # RGB channels don't matter for process_inpaint, but set them to white where pink for visualization
        mask_rgba[:, :, 0] = binmask  # R: white where pink
        mask_rgba[:, :, 1] = binmask  # G: white where pink  
        mask_rgba[:, :, 2] = binmask  # B: white where pink
        # Alpha: 0 (transparent) where pink → will become white after 255-alpha
        #        255 (opaque) everywhere else → will become black after 255-alpha
        mask_rgba[:, :, 3] = 255 - binmask  # Invert: pink areas get alpha=0, rest get alpha=255
        
        # Verify mask encoding
        alpha_zero_count = int((mask_rgba[:,:,3] == 0).sum())
        alpha_255_count = int((mask_rgba[:,:,3] == 255).sum())
        total_pixels = binmask.shape[0] * binmask.shape[1]
        log.info(f"Mask encoding: {alpha_zero_count} pixels with alpha=0 (pink), {alpha_255_count} pixels with alpha=255 (keep)")
        log.info(f"After 255-alpha conversion: {alpha_zero_count} will become white (255/remove), {alpha_255_count} will become black (0/keep)")
        
        # IMPORTANT: We need to use the ORIGINAL image WITHOUT pink paint for inpainting!
        # Remove pink from the original image before processing
        # Create a clean version: where pink was detected, keep original image colors
        img_clean = np.array(img.convert("RGBA"))
        # Where pink is detected, we want to inpaint, so we can leave it (or blend it out)
        # Actually, the model will inpaint over those areas, so we can pass the original
        # But for better results, we might want to remove the pink overlay first
        
        # Process with invert_mask=True (default) because process_inpaint expects alpha=0 for removal
        log.info(f"Starting inpainting process...")
        result = process_inpaint(img_clean, mask_rgba, invert_mask=True)
        log.info(f"Inpainting complete, result shape: {result.shape}")
        result_name = f"output_{uuid.uuid4().hex}.png"
        result_path = os.path.join(OUTPUT_DIR, result_name)
        result_image = Image.fromarray(result)
        result_image.save(result_path, "PNG", optimize=False, compress_level=1)
        try:
            spaces_info = _mirror_source_result_to_spaces(img, result_image)
        except Exception as spaces_err:
            log.error("Failed to mirror /remove-pink images to DigitalOcean Spaces: %s", spaces_err, exc_info=True)
        
        url: Optional[str] = None
        try:
            if request is not None:
                url = str(request.url_for("download_file", filename=result_name))
        except Exception:
            url = None
        
        logs.append({
            "result": result_name,
            "filename": image.filename,
            "pink_pixels": nonzero,
            "timestamp": datetime.utcnow().isoformat()
        })
        
        resp: Dict[str, str] = {"result": result_name, "pink_segments_detected": str(nonzero)}
        if url:
            resp["url"] = url
        if spaces_info:
            resp["source_space_key"] = spaces_info["source_key"]
            resp["result_space_key"] = spaces_info["result_key"]
        log_media_click(user_id, final_category_id, appname)
        return resp
    except Exception as e:
        status = "fail"
        error_msg = str(e)
        raise
    finally:
        # Always log to regular MongoDB (mandatory)
        end_time = time.time()
        response_time_ms = (end_time - start_time) * 1000
        log_doc = {
            "endpoint": "remove-pink",
            "output_id": result_name,
            "status": status,
            "timestamp": datetime.utcnow(),
            "ts": int(time.time()),
            "response_time_ms": response_time_ms,
        }
        # Store appname in api_logs if provided
        if appname:
            log_doc["appname"] = appname
        if error_msg:
            log_doc["error"] = error_msg
        if spaces_info:
            log_doc["source_space_key"] = spaces_info["source_key"]
            log_doc["result_space_key"] = spaces_info["result_key"]
        if mongo_logs is not None:
            try:
                log.info("Inserting log to MongoDB - Database: %s, Collection: %s", mongo_logs.database.name, mongo_logs.name)
                result = mongo_logs.insert_one(log_doc)
                log.info("Mongo log inserted successfully: _id=%s, output_id=%s, status=%s, db=%s, collection=%s", 
                        result.inserted_id, output_name, status, mongo_logs.database.name, mongo_logs.name)
                
                # Verify the insert by reading it back
                try:
                    verify_doc = mongo_logs.find_one({"_id": result.inserted_id})
                    if verify_doc:
                        log.info("Verified: Document exists in MongoDB after insert")
                    else:
                        log.error("WARNING: Document not found after insert! _id=%s", result.inserted_id)
                except Exception as verify_err:
                    log.warning("Could not verify insert: %s", verify_err)
            except Exception as mongo_err:
                log.error("Mongo log insert failed: %s, log_doc=%s", mongo_err, log_doc, exc_info=True)
        else:
            log.warning("MongoDB not configured, skipping log insert")


@app.get("/download/{filename}")
def download_file(filename: str):
    path = os.path.join(OUTPUT_DIR, filename)
    if not os.path.isfile(path):
        raise HTTPException(status_code=404, detail="file not found")
    return FileResponse(path)


@app.get("/result/{filename}")
def view_result(filename: str):
    """View result image directly in browser (same as download but with proper content-type for viewing)"""
    path = os.path.join(OUTPUT_DIR, filename)
    if not os.path.isfile(path):
        raise HTTPException(status_code=404, detail="file not found")
    return FileResponse(path, media_type="image/png")


@app.get("/logs")
def get_logs(_: None = Depends(bearer_auth)) -> JSONResponse:
    return JSONResponse(content=logs)

# import os
# import uuid
# import shutil
# import re
# from datetime import datetime, timedelta, date
# from io import BytesIO
# from typing import Dict, List, Optional,Any
# import numpy as np
# from fastapi import (
#     FastAPI,
#     UploadFile,
#     File,
#     HTTPException,
#     Depends,
#     Header,
#     Request,
#     Form,
# )
# from fastapi.responses import FileResponse, JSONResponse
# from pydantic import BaseModel
# from PIL import Image, UnidentifiedImageError
# import cv2
# import logging
# from gridfs import GridFS
# from gridfs.errors import NoFile

# from bson import ObjectId
# from pymongo import MongoClient
# import time

# # Load environment variables from .env if present
# try:
#     from dotenv import load_dotenv

#     load_dotenv()
# except Exception:
#     pass

# logging.basicConfig(level=logging.INFO)
# log = logging.getLogger("api")

# from src.core import process_inpaint

# # Directories (use writable space on HF Spaces)
# BASE_DIR = os.environ.get("DATA_DIR", "/data")
# if not os.path.isdir(BASE_DIR):
#     # Fallback to /tmp if /data not available
#     BASE_DIR = "/tmp"

# UPLOAD_DIR = os.path.join(BASE_DIR, "uploads")
# OUTPUT_DIR = os.path.join(BASE_DIR, "outputs")

# os.makedirs(UPLOAD_DIR, exist_ok=True)
# os.makedirs(OUTPUT_DIR, exist_ok=True)

# # Optional Bearer token: set env API_TOKEN to require auth; if not set, endpoints are open
# ENV_TOKEN = os.environ.get("API_TOKEN")

# app = FastAPI(title="Photo Object Removal API", version="1.0.0")

# # In-memory stores
# file_store: Dict[str, Dict[str, str]] = {}
# logs: List[Dict[str, str]] = []

# MONGO_URI = os.environ.get("MONGO_URI") or os.environ.get("MONGODB_URI")
# mongo_client = None
# mongo_db = None
# mongo_logs = None
# grid_fs = None

# if MONGO_URI:
#     try:
#         mongo_client = MongoClient(MONGO_URI)
#         # Try to get database from connection string first
#         try:
#             mongo_db = mongo_client.get_default_database()
#             log.info("Using database from connection string: %s", mongo_db.name)
#         except Exception as db_err:
#             mongo_db = None
#             log.warning("Could not extract database from connection string: %s", db_err)
        
#         # Fallback to 'object_remover' if no database in connection string
#         if mongo_db is None:
#             mongo_db = mongo_client["object_remover"]
#             log.info("Using default database: object_remover")
        
#         mongo_logs = mongo_db["api_logs"]
#         grid_fs = GridFS(mongo_db)
#         log.info("MongoDB connection initialized successfully - Database: %s, Collection: %s", mongo_db.name, mongo_logs.name)
#     except Exception as err:
#         log.error("Failed to initialize MongoDB connection: %s", err, exc_info=True)
#         log.warning("GridFS operations will be disabled. Set MONGO_URI or MONGODB_URI environment variable.")
# else:
#     log.warning("MONGO_URI not set. GridFS operations will be disabled. Upload endpoints will not work.")
# # if MONGO_URI:
# #     try:
# #         mongo_client = MongoClient(MONGO_URI)

# #         # 🔥 FORCE DB + COLLECTION
# #         mongo_db = mongo_client["logs"]
# #         mongo_logs = mongo_db["objectRemover"]

# #         log.info("MongoDB initialized → logs/objectRemover")
# #     except Exception as err:
# #         log.error("Failed to initialize MongoDB connection: %s", err, exc_info=True)
# #         mongo_logs = None
# # else:
# #     log.warning("MONGO_URI not set. Logging disabled.")
# # ✅ NEW: Separate Mongo for API Logs
# API_LOGS_MONGO_URI = os.environ.get("API_LOGS_MONGODB_URL")

# api_logs_client = None
# api_logs_db = None
# api_logs_collection = None

# if API_LOGS_MONGO_URI:
#     try:
#         api_logs_client = MongoClient(API_LOGS_MONGO_URI)
#         api_logs_db = api_logs_client["logs"]              # 🔥 logs database
#         api_logs_collection = api_logs_db["objectRemover"] # 🔥 objectRemover collection
#         log.info("API Logs Mongo initialized → logs/objectRemover")
#     except Exception as e:
#         log.error("Failed to initialize API Logs MongoDB: %s", e)
#         api_logs_collection = None
# else:
#     log.warning("API_LOGS_MONGODB_URL not set. API logging disabled.")
    
# ADMIN_MONGO_URI = os.environ.get("MONGODB_ADMIN")
# DEFAULT_CATEGORY_ID = "69368f722e46bd68ae188984"
# admin_media_clicks = None

# # Collage-maker MongoDB configuration
# COLLAGE_MAKER_MONGO_URI = os.environ.get("MONGODB_COLLAGE_MAKER")
# COLLAGE_MAKER_DB_NAME = os.environ.get("MONGODB_COLLAGE_MAKER_DB_NAME", "collage-maker")
# COLLAGE_MAKER_ADMIN_DB_NAME = os.environ.get("MONGODB_COLLAGE_MAKER_ADMIN_DB_NAME", "adminPanel")
# collage_maker_client = None
# collage_maker_db = None
# collage_maker_admin_db = None
# collage_maker_media_clicks = None
# collage_maker_categories = None

# # AI-Enhancer MongoDB configuration
# AI_ENHANCER_MONGO_URI = os.environ.get("MONGODB_AI_ENHANCER")
# AI_ENHANCER_DB_NAME = os.environ.get("MONGODB_AI_ENHANCER_DB_NAME", "ai-enhancer")
# AI_ENHANCER_ADMIN_DB_NAME = os.environ.get("MONGODB_AI_ENHANCER_ADMIN_DB_NAME", "test")
# ai_enhancer_client = None
# ai_enhancer_db = None
# ai_enhancer_admin_db = None
# ai_enhancer_media_clicks = None


# def get_collage_maker_client() -> Optional[MongoClient]:
#     """Get collage-maker MongoDB client."""
#     global collage_maker_client
#     if collage_maker_client is None and COLLAGE_MAKER_MONGO_URI:
#         try:
#             collage_maker_client = MongoClient(COLLAGE_MAKER_MONGO_URI)
#             log.info("Collage-maker MongoDB client initialized")
#         except Exception as err:
#             log.error("Failed to initialize collage-maker MongoDB client: %s", err)
#             collage_maker_client = None
#     return collage_maker_client


# def get_collage_maker_database() -> Optional[Any]:
#     """Get collage-maker database instance."""
#     global collage_maker_db
#     client = get_collage_maker_client()
#     if client is None:
#         return None
#     if collage_maker_db is None:
#         try:
#             collage_maker_db = client[COLLAGE_MAKER_DB_NAME]
#             log.info("Collage-maker database initialized: %s", COLLAGE_MAKER_DB_NAME)
#         except Exception as err:
#             log.error("Failed to get collage-maker database: %s", err)
#             collage_maker_db = None
#     return collage_maker_db


# def _init_collage_maker_mongo() -> None:
#     """Initialize collage-maker MongoDB connections."""
#     global collage_maker_admin_db, collage_maker_media_clicks, collage_maker_categories
#     client = get_collage_maker_client()
#     if client is None:
#         log.info("Collage-maker Mongo URI not provided; collage-maker features disabled")
#         return
#     try:
#         collage_maker_admin_db = client[COLLAGE_MAKER_ADMIN_DB_NAME]
#         collage_maker_media_clicks = collage_maker_admin_db["media_clicks"]
#         collage_maker_categories = collage_maker_admin_db["categories"]
#         log.info(
#             "Collage-maker admin initialized: db=%s, media_clicks=%s, categories=%s",
#             COLLAGE_MAKER_ADMIN_DB_NAME,
#             collage_maker_media_clicks.name,
#             collage_maker_categories.name,
#         )
#     except Exception as err:
#         log.error("Failed to init collage-maker admin Mongo: %s", err)
#         collage_maker_admin_db = None
#         collage_maker_media_clicks = None
#         collage_maker_categories = None


# _init_collage_maker_mongo()


# def get_ai_enhancer_client() -> Optional[MongoClient]:
#     """Get AI-Enhancer MongoDB client."""
#     global ai_enhancer_client
#     if ai_enhancer_client is None and AI_ENHANCER_MONGO_URI:
#         try:
#             ai_enhancer_client = MongoClient(AI_ENHANCER_MONGO_URI)
#             log.info("AI-Enhancer MongoDB client initialized")
#         except Exception as err:
#             log.error("Failed to initialize AI-Enhancer MongoDB client: %s", err)
#             ai_enhancer_client = None
#     return ai_enhancer_client


# def get_ai_enhancer_database() -> Optional[Any]:
#     """Get AI-Enhancer database instance."""
#     global ai_enhancer_db
#     client = get_ai_enhancer_client()
#     if client is None:
#         return None
#     if ai_enhancer_db is None:
#         try:
#             ai_enhancer_db = client[AI_ENHANCER_DB_NAME]
#             log.info("AI-Enhancer database initialized: %s", AI_ENHANCER_DB_NAME)
#         except Exception as err:
#             log.error("Failed to get AI-Enhancer database: %s", err)
#             ai_enhancer_db = None
#     return ai_enhancer_db


# def _init_ai_enhancer_mongo() -> None:
#     """Initialize AI-Enhancer MongoDB connections."""
#     global ai_enhancer_admin_db, ai_enhancer_media_clicks
#     client = get_ai_enhancer_client()
#     if client is None:
#         log.info("AI-Enhancer Mongo URI not provided; AI-Enhancer features disabled")
#         return
#     try:
#         ai_enhancer_admin_db = client[AI_ENHANCER_ADMIN_DB_NAME]
#         ai_enhancer_media_clicks = ai_enhancer_admin_db["media_clicks"]
#         log.info(
#             "AI-Enhancer admin initialized: db=%s, media_clicks=%s",
#             AI_ENHANCER_ADMIN_DB_NAME,
#             ai_enhancer_media_clicks.name,
#         )
#     except Exception as err:
#         log.error("Failed to init AI-Enhancer admin Mongo: %s", err)
#         ai_enhancer_admin_db = None
#         ai_enhancer_media_clicks = None


# _init_ai_enhancer_mongo()


# def get_category_id_from_collage_maker() -> Optional[str]:
#     """Query category ID from collage-maker categories collection."""
#     if collage_maker_categories is None:
#         log.warning("Collage-maker categories collection not initialized")
#         return None
#     try:
#         # Query the categories collection - you may need to adjust the query based on your schema
#         # This assumes there's a default category or we get the first one
#         category_doc = collage_maker_categories.find_one()
#         if category_doc:
#             category_id = str(category_doc.get("_id", ""))
#             log.info("Found category ID from collage-maker: %s", category_id)
#             return category_id
#         else:
#             log.warning("No categories found in collage-maker collection")
#             return None
#     except Exception as err:
#         log.error("Failed to query collage-maker categories: %s", err)
#         return None


# def _init_admin_mongo() -> None:
#     global admin_media_clicks
#     if not ADMIN_MONGO_URI:
#         log.info("Admin Mongo URI not provided; media click logging disabled")
#         return
#     try:
#         admin_client = MongoClient(ADMIN_MONGO_URI)
#         # get_default_database() extracts database from connection string (e.g., /adminPanel)
#         try:
#             admin_db = admin_client.get_default_database()
#         except Exception as db_err:
#             admin_db = None
#             log.warning("Admin Mongo URI has no default DB; error=%s", db_err)
#         if admin_db is None:
#             # Fallback to provided default for this app
#             admin_db = admin_client["object_remover"]
#             log.warning("No database in connection string, defaulting to 'object_remover'")
        
#         admin_media_clicks = admin_db["media_clicks"]
#         log.info(
#             "Admin media click logging initialized: db=%s collection=%s",
#             admin_db.name,
#             admin_media_clicks.name,
#         )
#         try:
#             admin_media_clicks.drop_index("user_id_1_header_1_media_id_1")
#             log.info("Dropped legacy index user_id_1_header_1_media_id_1")
#         except Exception as idx_err:
#             # Index drop failure is non-critical (often permission issue)
#             if "Unauthorized" not in str(idx_err):
#                 log.info("Skipping legacy index drop: %s", idx_err)
#     except Exception as err:
#         log.error("Failed to init admin Mongo client: %s", err)
#         admin_media_clicks = None


# _init_admin_mongo()


# def _admin_logging_status() -> Dict[str, object]:
#     if admin_media_clicks is None:
#         return {
#             "enabled": False,
#             "db": None,
#             "collection": None,
#         }
#     return {
#         "enabled": True,
#         "db": admin_media_clicks.database.name,
#         "collection": admin_media_clicks.name,
#     }


# def _save_upload_to_gridfs(upload: UploadFile, file_type: str) -> str:
#     """Store an uploaded file into GridFS and return its ObjectId string."""
#     if grid_fs is None:
#         raise HTTPException(
#             status_code=503,
#             detail="MongoDB/GridFS not configured. Set MONGO_URI or MONGODB_URI environment variable."
#         )
#     data = upload.file.read()
#     if not data:
#         raise HTTPException(status_code=400, detail=f"{file_type} file is empty")
#     oid = grid_fs.put(
#         data,
#         filename=upload.filename or f"{file_type}.bin",
#         contentType=upload.content_type,
#         metadata={"type": file_type},
#     )
#     return str(oid)


# def _read_gridfs_bytes(file_id: str, expected_type: str) -> bytes:
#     """Fetch raw bytes from GridFS and validate the stored type metadata."""
#     if grid_fs is None:
#         raise HTTPException(
#             status_code=503,
#             detail="MongoDB/GridFS not configured. Set MONGO_URI or MONGODB_URI environment variable."
#         )
#     try:
#         oid = ObjectId(file_id)
#     except Exception:
#         raise HTTPException(status_code=404, detail=f"{expected_type}_id invalid")

#     try:
#         grid_out = grid_fs.get(oid)
#     except NoFile:
#         raise HTTPException(status_code=404, detail=f"{expected_type}_id not found")

#     meta = grid_out.metadata or {}
#     stored_type = meta.get("type")
#     if stored_type and stored_type != expected_type:
#         raise HTTPException(status_code=404, detail=f"{expected_type}_id not found")

#     return grid_out.read()


# def _load_rgba_image_from_gridfs(file_id: str, expected_type: str) -> Image.Image:
#     """Load an image from GridFS and convert to RGBA."""
#     data = _read_gridfs_bytes(file_id, expected_type)
#     try:
#         img = Image.open(BytesIO(data))
#     except UnidentifiedImageError:
#         raise HTTPException(status_code=422, detail=f"{expected_type} is not a valid image")
#     return img.convert("RGBA")


# def _build_ai_edit_daily_count(
#     existing: Optional[List[Dict[str, object]]],
#     today: date,
# ) -> List[Dict[str, object]]:
#     """
#     Build / extend the ai_edit_daily_count array with the following rules:

#     - Case A (no existing data): return [{date: today, count: 1}]
#     - Case B (today already recorded): return list unchanged
#     - Case C (gap in days): fill missing days with count=0 and append today with count=1

#     Additionally, the returned list is capped to the most recent 32 entries.

#     The stored "date" value is a midnight UTC (naive UTC) datetime for the given day.
#     """

#     def _to_date_only(value: object) -> date:
#         if isinstance(value, datetime):
#             return value.date()
#         if isinstance(value, date):
#             return value
#         # Fallback: try parsing ISO string "YYYY-MM-DD" or full datetime
#         try:
#             text = str(value)
#             if len(text) == 10:
#                 return datetime.strptime(text, "%Y-%m-%d").date()
#             return datetime.fromisoformat(text).date()
#         except Exception:
#             # If parsing fails, just treat as today to avoid crashing
#             return today

#     # Case A: first ever use (no array yet)
#     if not existing:
#         return [
#             {
#                 "date": datetime(today.year, today.month, today.day),
#                 "count": 1,
#             }
#         ]

#     # Work on a shallow copy so we don't mutate original in-place
#     result: List[Dict[str, object]] = list(existing)

#     last_entry = result[-1] if result else None
#     if not last_entry or "date" not in last_entry:
#         # If structure is unexpected, re-initialize safely
#         return [
#             {
#                 "date": datetime(today.year, today.month, today.day),
#                 "count": 1,
#             }
#         ]

#     last_date = _to_date_only(last_entry["date"])

#     # If somehow the last stored date is in the future, do nothing to avoid corrupting history
#     if last_date > today:
#         return result

#     # Case B: today's date already present as the last entry → unchanged
#     if last_date == today:
#         return result

#     # Case C: there is a gap, fill missing days with count=0 and append today with count=1
#     cursor = last_date + timedelta(days=1)
#     while cursor < today:
#         result.append(
#             {
#                 "date": datetime(cursor.year, cursor.month, cursor.day),
#                 "count": 0,
#             }
#         )
#         cursor += timedelta(days=1)

#     # Finally add today's presence indicator
#     result.append(
#         {
#             "date": datetime(today.year, today.month, today.day),
#             "count": 1,
#         }
#     )

#     # Sort by date ascending (older dates first) to guarantee stable ordering:
#     # [oldest, ..., newest]
#     try:
#         result.sort(key=lambda entry: _to_date_only(entry.get("date")))
#     except Exception:
#         # If anything goes wrong during sort, fall back to current ordering
#         pass

#     # Enforce 32-entry limit (keep the most recent 32 days)
#     if len(result) > 32:
#         result = result[-32:]

#     return result

# def bearer_auth(authorization: Optional[str] = Header(default=None)) -> None:
#     if not ENV_TOKEN:
#         return
#     if authorization is None or not authorization.lower().startswith("bearer "):
#         raise HTTPException(status_code=401, detail="Unauthorized")
#     token = authorization.split(" ", 1)[1]
#     if token != ENV_TOKEN:
#         raise HTTPException(status_code=403, detail="Forbidden")


# class InpaintRequest(BaseModel):
#     image_id: str
#     mask_id: str
#     invert_mask: bool = True  # True => selected/painted area is removed
#     passthrough: bool = False  # If True, return the original image unchanged
#     prompt: Optional[str] = None  # Optional: describe what to remove
#     user_id: Optional[str] = None
#     category_id: Optional[str] = None
#     appname: Optional[str] = None  # Optional: app name (e.g., "collage-maker")


# class SimpleRemoveRequest(BaseModel):
#     image_id: str  # Image with pink/magenta segments to remove


# def _coerce_object_id(value: Optional[str]) -> ObjectId:
#     if value is None:
#         return ObjectId()
#     value_str = str(value).strip()
#     if re.fullmatch(r"[0-9a-fA-F]{24}", value_str):
#         return ObjectId(value_str)
#     if value_str.isdigit():
#         hex_str = format(int(value_str), "x")
#         if len(hex_str) > 24:
#             hex_str = hex_str[-24:]
#         hex_str = hex_str.rjust(24, "0")
#         return ObjectId(hex_str)
#     return ObjectId()


# def _coerce_category_id(category_id: Optional[str]) -> ObjectId:
#     raw = category_id or DEFAULT_CATEGORY_ID
#     raw_str = str(raw).strip()
#     if re.fullmatch(r"[0-9a-fA-F]{24}", raw_str):
#         return ObjectId(raw_str)
#     return _coerce_object_id(raw_str)


# def log_media_click(user_id: Optional[str], category_id: Optional[str], appname: Optional[str] = None) -> None:
#     """Log to admin media_clicks collection only if user_id is provided.
    
#     If appname='collage-maker', logs to collage-maker MongoDB instead of regular admin MongoDB.
#     If appname='AI-Enhancer' (case-insensitive), logs to AI-Enhancer MongoDB.
#     """
#     # Determine which media_clicks collection to use
#     target_media_clicks = None
#     appname_lower = appname.lower() if appname else None
    
#     if appname_lower == "collage-maker":
#         target_media_clicks = collage_maker_media_clicks
#         if target_media_clicks is None:
#             log.warning("Collage-maker media_clicks not initialized, skipping log")
#             return
#     elif appname_lower == "ai-enhancer":
#         target_media_clicks = ai_enhancer_media_clicks
#         if target_media_clicks is None:
#             log.warning("AI-Enhancer media_clicks not initialized, skipping log")
#             return
#     else:
#         target_media_clicks = admin_media_clicks
#         if target_media_clicks is None:
#             return
    
#     # Only log if user_id is provided (not None/empty)
#     if not user_id or not user_id.strip():
#         return
#     try:
#         user_obj = _coerce_object_id(user_id)
#         category_obj = _coerce_category_id(category_id)
#         now = datetime.utcnow()
#         today = now.date()

#         doc = target_media_clicks.find_one({"userId": user_obj})
#         if doc:
#             existing_daily = doc.get("ai_edit_daily_count")
#             updated_daily = _build_ai_edit_daily_count(existing_daily, today)
#             categories = doc.get("categories") or []
#             if any(cat.get("categoryId") == category_obj for cat in categories):
#                 # Category exists: increment click_count and ai_edit_complete, update dates
#                 target_media_clicks.update_one(
#                     {"_id": doc["_id"], "categories.categoryId": category_obj},
#                     {
#                         "$inc": {
#                             "categories.$.click_count": 1,
#                             "ai_edit_complete": 1,  # $inc handles missing fields (backward compatible)
#                         },
#                         "$set": {
#                             "categories.$.lastClickedAt": now,
#                             "updatedAt": now,
#                             "ai_edit_last_date": now,
#                             "ai_edit_daily_count": updated_daily,
#                         },
#                     },
#                 )
#             else:
#                 # New category to existing document: push category, increment ai_edit_complete
#                 target_media_clicks.update_one(
#                     {"_id": doc["_id"]},
#                     {
#                         "$push": {
#                             "categories": {
#                                 "categoryId": category_obj,
#                                 "click_count": 1,
#                                 "lastClickedAt": now,
#                             }
#                         },
#                         "$inc": {"ai_edit_complete": 1},  # $inc handles missing fields
#                         "$set": {
#                             "updatedAt": now,
#                             "ai_edit_last_date": now,
#                             "ai_edit_daily_count": updated_daily,
#                         },
#                     },
#                 )
#         else:
#             # New user: create document with default ai_edit_complete=0, then increment to 1
#             daily_for_new = _build_ai_edit_daily_count(None, today)
#             target_media_clicks.update_one(
#                 {"userId": user_obj},
#                 {
#                     "$setOnInsert": {
#                         "userId": user_obj,
#                         "categories": [
#                             {
#                                 "categoryId": category_obj,
#                                 "click_count": 1,
#                                 "lastClickedAt": now,
#                             }
#                         ],
#                         "createdAt": now,
#                         "ai_edit_daily_count": daily_for_new,
#                     },
#                     "$inc": {"ai_edit_complete": 1},  # Increment to 1 on first use
#                     "$set": {
#                         "updatedAt": now,
#                         "ai_edit_last_date": now,
#                     },
#                 },
#                 upsert=True,
#             )
#     except Exception as err:
#         err_str = str(err)
#         appname_lower = appname.lower() if appname else None
#         if appname_lower == "collage-maker":
#             target_name = "collage-maker"
#         elif appname_lower == "ai-enhancer":
#             target_name = "AI-Enhancer"
#         else:
#             target_name = "admin"
#         if "Unauthorized" in err_str or "not authorized" in err_str.lower():
#             log.warning(
#                 "%s media click logging failed (permissions): user lacks read/write on db=%s collection=%s. "
#                 "Check MongoDB user permissions.",
#                 target_name,
#                 target_media_clicks.database.name,
#                 target_media_clicks.name,
#             )
#         else:
#             log.warning("%s media click logging failed: %s", target_name, err)


# @app.get("/")
# def root() -> Dict[str, Any]:
#     return {
#         "success": True,
#         "message": "Object Remover API",
#         "data": {
#             "version": "1.0.0",
#             "product_name": "Beauty Camera - GlowCam AI Studio",
#             "released_by": "LogicGo Infotech"
#         }
#     }



# @app.get("/health")
# def health() -> Dict[str, str]:
#     return {"status": "healthy"}


# @app.get("/logging-status")
# def logging_status(_: None = Depends(bearer_auth)) -> Dict[str, object]:
#     """Helper endpoint to verify admin media logging wiring (no secrets exposed)."""
#     return _admin_logging_status()


# @app.get("/mongo-status")
# def mongo_status(_: None = Depends(bearer_auth)) -> Dict[str, object]:
#     """Check MongoDB connection status and verify data storage."""
#     status = {
#         "mongo_configured": MONGO_URI is not None,
#         "mongo_connected": mongo_client is not None,
#         "database": mongo_db.name if mongo_db else None,
#         "collection": mongo_logs.name if mongo_logs else None,
#         "admin_logging": _admin_logging_status(),
#     }
    
#     # Try to count documents in api_logs collection
#     if mongo_logs is not None:
#         try:
#             count = mongo_logs.count_documents({})
#             status["api_logs_count"] = count
#             # Get latest 5 documents
#             latest_docs = list(mongo_logs.find().sort("timestamp", -1).limit(5))
#             status["recent_logs"] = []
#             for doc in latest_docs:
#                 doc_dict = {
#                     "_id": str(doc.get("_id")),
#                     "output_id": doc.get("output_id"),
#                     "status": doc.get("status"),
#                     "timestamp": doc.get("timestamp").isoformat() if isinstance(doc.get("timestamp"), datetime) else str(doc.get("timestamp")),
#                 }
#                 if "input_image_id" in doc:
#                     doc_dict["input_image_id"] = doc.get("input_image_id")
#                 if "input_mask_id" in doc:
#                     doc_dict["input_mask_id"] = doc.get("input_mask_id")
#                 if "error" in doc:
#                     doc_dict["error"] = doc.get("error")
#                 status["recent_logs"].append(doc_dict)
            
#             # Get latest document for backward compatibility
#             if latest_docs:
#                 latest = latest_docs[0]
#                 status["latest_log"] = {
#                     "_id": str(latest.get("_id")),
#                     "output_id": latest.get("output_id"),
#                     "status": latest.get("status"),
#                     "timestamp": latest.get("timestamp").isoformat() if isinstance(latest.get("timestamp"), datetime) else str(latest.get("timestamp")),
#                 }
#         except Exception as err:
#             status["api_logs_error"] = str(err)
#             log.error("Error querying MongoDB: %s", err, exc_info=True)
    
#     return status


# @app.post("/upload-image")
# def upload_image(image: UploadFile = File(...), _: None = Depends(bearer_auth)) -> Dict[str, str]:
#     file_id = _save_upload_to_gridfs(image, "image")
#     logs.append({"id": file_id, "filename": image.filename, "type": "image", "timestamp": datetime.utcnow().isoformat()})
#     return {"id": file_id, "filename": image.filename}


# @app.post("/upload-mask")
# def upload_mask(mask: UploadFile = File(...), _: None = Depends(bearer_auth)) -> Dict[str, str]:
#     file_id = _save_upload_to_gridfs(mask, "mask")
#     logs.append({"id": file_id, "filename": mask.filename, "type": "mask", "timestamp": datetime.utcnow().isoformat()})
#     return {"id": file_id, "filename": mask.filename}


# def _compress_image(image_path: str, output_path: str, quality: int = 85) -> None:
#     """
#     Compress an image to reduce file size.
#     Converts to JPEG format with specified quality to achieve smaller file size.
#     """
#     img = Image.open(image_path)
#     # Convert RGBA to RGB if needed (JPEG doesn't support alpha)
#     if img.mode == "RGBA":
#         rgb_img = Image.new("RGB", img.size, (255, 255, 255))
#         rgb_img.paste(img, mask=img.split()[3])  # Use alpha channel as mask
#         img = rgb_img
#     elif img.mode != "RGB":
#         img = img.convert("RGB")
    
#     # Save as JPEG with quality setting for compression
#     img.save(output_path, "JPEG", quality=quality, optimize=True)


# def _load_rgba_mask_from_image(img: Image.Image) -> np.ndarray:
#     """
#     Convert mask image to RGBA format (black/white mask).
#     Standard convention: white (255) = area to remove, black (0) = area to keep
#     Returns RGBA with white in RGB channels where removal is needed, alpha=255
#     """
#     if img.mode != "RGBA":
#         # For RGB/Grayscale masks: white (value>128) = remove, black (value<=128) = keep
#         gray = img.convert("L")
#         arr = np.array(gray)
#         # Create proper black/white mask: white pixels (>128) = remove, black (<=128) = keep
#         mask_bw = np.where(arr > 128, 255, 0).astype(np.uint8)
        
#         rgba = np.zeros((img.height, img.width, 4), dtype=np.uint8)
#         rgba[:, :, 0] = mask_bw  # R
#         rgba[:, :, 1] = mask_bw  # G
#         rgba[:, :, 2] = mask_bw  # B
#         rgba[:, :, 3] = 255  # Fully opaque
#         log.info(f"Loaded {img.mode} mask: {int((mask_bw > 0).sum())} white pixels (to remove)")
#         return rgba
    
#     # For RGBA: check if alpha channel is meaningful
#     arr = np.array(img)
#     alpha = arr[:, :, 3]
#     rgb = arr[:, :, :3]
    
#     # If alpha is mostly opaque everywhere (mean > 200), treat RGB channels as mask values
#     if alpha.mean() > 200:
#         # Use RGB to determine mask: white/bright in RGB = remove
#         gray = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY)
#         # Also detect magenta specifically
#         magenta = np.all(rgb == [255, 0, 255], axis=2).astype(np.uint8) * 255
#         mask_bw = np.maximum(np.where(gray > 128, 255, 0).astype(np.uint8), magenta)
        
#         rgba = arr.copy()
#         rgba[:, :, 0] = mask_bw  # R
#         rgba[:, :, 1] = mask_bw  # G
#         rgba[:, :, 2] = mask_bw  # B
#         rgba[:, :, 3] = 255  # Fully opaque
#         log.info(f"Loaded RGBA mask (RGB-based): {int((mask_bw > 0).sum())} white pixels (to remove)")
#         return rgba
    
#     # Alpha channel encodes the mask - convert to RGB-based
#     # Transparent areas (alpha < 128) = remove, Opaque areas = keep
#     mask_bw = np.where(alpha < 128, 255, 0).astype(np.uint8)
#     rgba = arr.copy()
#     rgba[:, :, 0] = mask_bw
#     rgba[:, :, 1] = mask_bw
#     rgba[:, :, 2] = mask_bw
#     rgba[:, :, 3] = 255
#     log.info(f"Loaded RGBA mask (alpha-based): {int((mask_bw > 0).sum())} white pixels (to remove)")
#     return rgba

# @app.post("/inpaint")
# def inpaint(req: InpaintRequest, request: Request, _: None = Depends(bearer_auth)) -> Dict[str, str]:
#     start_time = time.time()
#     status = "success"
#     error_msg = None
#     output_name = None
#     compressed_url = None

#     try:
#         # Handle appname="collage-maker": get category_id from collage-maker if not provided
#         category_id = req.category_id
#         if req.appname == "collage-maker" and not category_id:
#             category_id = get_category_id_from_collage_maker()
#             if category_id:
#                 log.info("Using category_id from collage-maker: %s", category_id)

#         img_rgba = _load_rgba_image_from_gridfs(req.image_id, "image")
#         mask_img = _load_rgba_image_from_gridfs(req.mask_id, "mask")
#         mask_rgba = _load_rgba_mask_from_image(mask_img)

#         if req.passthrough:
#             result = np.array(img_rgba.convert("RGB"))
#         else:
#             result = process_inpaint(
#                 np.array(img_rgba), 
#                 mask_rgba, 
#                 invert_mask=req.invert_mask,
#                 prompt=req.prompt,
#             )

#         output_name = f"output_{uuid.uuid4().hex}.png"
#         output_path = os.path.join(OUTPUT_DIR, output_name)

#         Image.fromarray(result).save(
#             output_path, "PNG", optimize=False, compress_level=1
#         )

#         # Create compressed version
#         compressed_name = f"compressed_{output_name.replace('.png', '.jpg')}"
#         compressed_path = os.path.join(OUTPUT_DIR, compressed_name)
#         try:
#             # _compress_image(output_path, compressed_path, quality=85)
#             # # compressed_url = str(request.url_for("download_file", filename=compressed_name))
#             # compressed_url = str(request.url_for("download_file", filename=compressed_name).replace("http://", "https://"))
#             _compress_image(output_path, compressed_path, quality=85)
#             compressed_url = str(
#                 request.url_for("download_file", filename=compressed_name)
#             ).replace("http://", "https://")
#         except Exception as compress_err:
#             log.warning("Failed to create compressed image: %s", compress_err)
#             compressed_url = None

#         log_media_click(req.user_id, category_id, req.appname)
#         response = {"result": output_name}
#         if compressed_url:
#             response["Compressed_Image_URL"] = compressed_url
#         return response

#     except Exception as e:
#         status = "fail"
#         error_msg = str(e)
#         raise

#     finally:
#         end_time = time.time()
#         response_time_ms = (end_time - start_time) * 1000

#         # log_doc = {
#         #     "input_image_id": req.image_id,
#         #     "input_mask_id": req.mask_id,
#         #     "output_id": output_name,
#         #     "status": status,
#         #     "timestamp": datetime.utcnow(),
#         #     "ts": int(time.time()),
#         #     "response_time_ms": response_time_ms
#         # }
#         log_doc = {
#             "endpoint": "/inpaint",
#             "status": status,
#             "response_time_ms": float(response_time_ms),
#             "timestamp": datetime.utcnow(),
#             "appname": req.appname if req.appname else "None",
#             "error": error_msg
#         }

#         # Store appname in api_logs if provided
#         if req.appname:
#             log_doc["appname"] = req.appname

#         if error_msg:
#             log_doc["error"] = error_msg

#         # if mongo_logs is not None:
#         #     try:
#         #         log.info("Inserting log to MongoDB - Database: %s, Collection: %s", mongo_logs.database.name, mongo_logs.name)
#         #         log.debug("Log document: %s", log_doc)
#         #         result = mongo_logs.insert_one(log_doc)
#         #         log.info("Mongo log inserted successfully: _id=%s, output_id=%s, status=%s, db=%s, collection=%s", 
#         #                 result.inserted_id, output_name, status, mongo_logs.database.name, mongo_logs.name)
                
#         #         # Verify the insert by reading it back
#         #         try:
#         #             verify_doc = mongo_logs.find_one({"_id": result.inserted_id})
#         #             if verify_doc:
#         #                 log.info("Verified: Document exists in MongoDB after insert")
#         #             else:
#         #                 log.error("WARNING: Document not found after insert! _id=%s", result.inserted_id)
#         #         except Exception as verify_err:
#         #             log.warning("Could not verify insert: %s", verify_err)
#         #     except Exception as mongo_err:
#         #         log.error("Mongo log insert failed: %s, log_doc=%s", mongo_err, log_doc, exc_info=True)
#         # else:
#         #     log.warning("MongoDB not configured, skipping log insert")
#         if api_logs_collection is not None:
#             try:
#                 api_logs_collection.insert_one(log_doc)
#                 log.info("API log inserted into logs/objectRemover")
#             except Exception as e:
#                 log.error("Failed to insert API log: %s", e)

# # @app.post("/inpaint")
# # def inpaint(req: InpaintRequest, _: None = Depends(bearer_auth)) -> Dict[str, str]:
# #     if req.image_id not in file_store or file_store[req.image_id]["type"] != "image":
# #         raise HTTPException(status_code=404, detail="image_id not found")
# #     if req.mask_id not in file_store or file_store[req.mask_id]["type"] != "mask":
# #         raise HTTPException(status_code=404, detail="mask_id not found")

# #     img_rgba = _load_rgba_image(file_store[req.image_id]["path"])
# #     mask_img = Image.open(file_store[req.mask_id]["path"])  # may be RGB/gray/RGBA
# #     mask_rgba = _load_rgba_mask_from_image(mask_img)

# #     # Debug: check mask before processing
# #     white_pixels = int((mask_rgba[:,:,0] > 128).sum())
# #     log.info(f"Inpaint request: mask has {white_pixels} white pixels, invert_mask={req.invert_mask}")

# #     if req.passthrough:
# #         result = np.array(img_rgba.convert("RGB"))
# #     else:
# #         result = process_inpaint(np.array(img_rgba), mask_rgba, invert_mask=req.invert_mask)
# #     result_name = f"output_{uuid.uuid4().hex}.png"
# #     result_path = os.path.join(OUTPUT_DIR, result_name)
# #     Image.fromarray(result).save(result_path, "PNG", optimize=False, compress_level=1)

# #     logs.append({"result": result_name, "timestamp": datetime.utcnow().isoformat()})
# #     return {"result": result_name}


# @app.post("/inpaint-url")
# def inpaint_url(req: InpaintRequest, request: Request, _: None = Depends(bearer_auth)) -> Dict[str, str]:
#     """Same as /inpaint but returns a JSON with a public download URL instead of image bytes."""
#     start_time = time.time()
#     status = "success"
#     error_msg = None
#     result_name = None

#     try:
#         # Handle appname="collage-maker": get category_id from collage-maker if not provided
#         category_id = req.category_id
#         if req.appname == "collage-maker" and not category_id:
#             category_id = get_category_id_from_collage_maker()
#             if category_id:
#                 log.info("Using category_id from collage-maker: %s", category_id)

#         img_rgba = _load_rgba_image_from_gridfs(req.image_id, "image")
#         mask_img = _load_rgba_image_from_gridfs(req.mask_id, "mask")  # may be RGB/gray/RGBA
#         mask_rgba = _load_rgba_mask_from_image(mask_img)

#         if req.passthrough:
#             result = np.array(img_rgba.convert("RGB"))
#         else:
#             result = process_inpaint(
#                 np.array(img_rgba),
#                 mask_rgba,
#                 invert_mask=req.invert_mask,
#                 prompt=req.prompt,
#             )
#         result_name = f"output_{uuid.uuid4().hex}.png"
#         result_path = os.path.join(OUTPUT_DIR, result_name)
#         Image.fromarray(result).save(result_path, "PNG", optimize=False, compress_level=1)

#         url = str(request.url_for("download_file", filename=result_name))
#         logs.append({"result": result_name, "url": url, "timestamp": datetime.utcnow().isoformat()})
#         log_media_click(req.user_id, category_id, req.appname)
#         return {"result": result_name, "url": url}
#     except Exception as e:
#         status = "fail"
#         error_msg = str(e)
#         raise
#     finally:
#         # Always log to regular MongoDB (mandatory)
#         end_time = time.time()
#         response_time_ms = (end_time - start_time) * 1000
#         log_doc = {
#             "input_image_id": req.image_id,
#             "input_mask_id": req.mask_id,
#             "output_id": result_name,
#             "status": status,
#             "timestamp": datetime.utcnow(),
#             "ts": int(time.time()),
#             "response_time_ms": response_time_ms,
#         }
#         # Store appname in api_logs if provided
#         if req.appname:
#             log_doc["appname"] = req.appname
#         if error_msg:
#             log_doc["error"] = error_msg
#         if mongo_logs is not None:
#             try:
#                 log.info("Inserting log to MongoDB - Database: %s, Collection: %s", mongo_logs.database.name, mongo_logs.name)
#                 result = mongo_logs.insert_one(log_doc)
#                 log.info("Mongo log inserted successfully: _id=%s, output_id=%s, status=%s, db=%s, collection=%s", 
#                         result.inserted_id, output_name, status, mongo_logs.database.name, mongo_logs.name)
                
#                 # Verify the insert by reading it back
#                 try:
#                     verify_doc = mongo_logs.find_one({"_id": result.inserted_id})
#                     if verify_doc:
#                         log.info("Verified: Document exists in MongoDB after insert")
#                     else:
#                         log.error("WARNING: Document not found after insert! _id=%s", result.inserted_id)
#                 except Exception as verify_err:
#                     log.warning("Could not verify insert: %s", verify_err)
#             except Exception as mongo_err:
#                 log.error("Mongo log insert failed: %s, log_doc=%s", mongo_err, log_doc, exc_info=True)
#         else:
#             log.warning("MongoDB not configured, skipping log insert")


# @app.post("/inpaint-multipart")
# def inpaint_multipart(
#     image: UploadFile = File(...),
#     mask: UploadFile = File(...),
#     request: Request = None,
#     invert_mask: bool = True,
#     mask_is_painted: bool = False,  # if True, mask file is the painted-on image (e.g., black strokes on original)
#     passthrough: bool = False,
#     prompt: Optional[str] = Form(None),
#     user_id: Optional[str] = Form(None),
#     category_id: Optional[str] = Form(None),
#     appname: Optional[str] = Form(None),
#     _: None = Depends(bearer_auth),
# ) -> Dict[str, str]:
#     start_time = time.time()
#     status = "success"
#     error_msg = None
#     result_name = None
    
#     try:
#         # Handle appname="collage-maker": get category_id from collage-maker if not provided
#         final_category_id = category_id
#         if appname == "collage-maker" and not final_category_id:
#             final_category_id = get_category_id_from_collage_maker()
#             if final_category_id:
#                 log.info("Using category_id from collage-maker: %s", final_category_id)
        
#         # Load in-memory
#         img = Image.open(image.file).convert("RGBA")
#         m = Image.open(mask.file).convert("RGBA")

#         if passthrough:
#             # Just echo the input image, ignore mask
#             result = np.array(img.convert("RGB"))
#             result_name = f"output_{uuid.uuid4().hex}.png"
#             result_path = os.path.join(OUTPUT_DIR, result_name)
#             Image.fromarray(result).save(result_path, "PNG", optimize=False, compress_level=1)

#             url: Optional[str] = None
#             try:
#                 if request is not None:
#                     url = str(request.url_for("download_file", filename=result_name))
#             except Exception:
#                 url = None

#             entry: Dict[str, str] = {"result": result_name, "timestamp": datetime.utcnow().isoformat()}
#             if url:
#                 entry["url"] = url
#             logs.append(entry)
#             resp: Dict[str, str] = {"result": result_name}
#             if url:
#                 resp["url"] = url
#             log_media_click(user_id, final_category_id, appname)
#             return resp

#         if mask_is_painted:
#             # Auto-detect pink/magenta paint and convert to black/white mask
#             # White pixels = areas to remove, Black pixels = areas to keep
#             log.info("Auto-detecting pink/magenta paint from uploaded image...")
            
#             m_rgb = cv2.cvtColor(np.array(m), cv2.COLOR_RGBA2RGB)
            
#             # Detect pink/magenta using fixed RGB bounds (same as /remove-pink)
#             lower = np.array([150, 0, 100], dtype=np.uint8)
#             upper = np.array([255, 120, 255], dtype=np.uint8)
#             magenta_detected = (
#                 (m_rgb[:, :, 0] >= lower[0]) & (m_rgb[:, :, 0] <= upper[0]) &
#                 (m_rgb[:, :, 1] >= lower[1]) & (m_rgb[:, :, 1] <= upper[1]) &
#                 (m_rgb[:, :, 2] >= lower[2]) & (m_rgb[:, :, 2] <= upper[2])
#             ).astype(np.uint8) * 255
            
#             # Method 2: Also check if original image was provided to find differences
#             if img is not None:
#                 img_rgb = cv2.cvtColor(np.array(img), cv2.COLOR_RGBA2RGB)
#                 if img_rgb.shape == m_rgb.shape:
#                     diff = cv2.absdiff(img_rgb, m_rgb)
#                     gray_diff = cv2.cvtColor(diff, cv2.COLOR_RGB2GRAY)
#                     # Any significant difference (>50) could be paint
#                     diff_mask = (gray_diff > 50).astype(np.uint8) * 255
#                     # Combine with magenta detection
#                     binmask = cv2.bitwise_or(magenta_detected, diff_mask)
#                 else:
#                     binmask = magenta_detected
#             else:
#                 # No original image provided, use magenta detection only
#                 binmask = magenta_detected
            
#             # Clean up the mask: remove noise and fill small holes
#             kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
#             # Close small gaps in the mask
#             binmask = cv2.morphologyEx(binmask, cv2.MORPH_CLOSE, kernel, iterations=2)
#             # Remove small noise
#             binmask = cv2.morphologyEx(binmask, cv2.MORPH_OPEN, kernel, iterations=1)
            
#             nonzero = int((binmask > 0).sum())
#             log.info("Pink/magenta paint detected: %d pixels marked for removal (white)", nonzero)
            
#             # If very few pixels detected, assume the user may already be providing a BW mask
#             # and proceed without forcing strict detection
            
#             if nonzero < 50:
#                 log.error("CRITICAL: Could not detect pink/magenta paint! Returning original image.")
#                 result = np.array(img.convert("RGB")) if img else np.array(m.convert("RGB"))
#                 result_name = f"output_{uuid.uuid4().hex}.png"
#                 result_path = os.path.join(OUTPUT_DIR, result_name)
#                 Image.fromarray(result).save(result_path, "PNG", optimize=False, compress_level=1)
#                 return {"result": result_name, "error": "pink/magenta paint detection failed - very few pixels detected"}
            
#             # Create binary mask: Pink pixels → white (255), Everything else → black (0)
#             # Encode in RGBA format for process_inpaint
#             # process_inpaint does: mask = 255 - mask[:,:,3]
#             # So: alpha=0 (transparent/pink) → becomes 255 (white/remove)
#             #     alpha=255 (opaque/keep) → becomes 0 (black/keep)
#             mask_rgba = np.zeros((binmask.shape[0], binmask.shape[1], 4), dtype=np.uint8)
#             mask_rgba[:, :, 0] = binmask  # R: white where pink (for visualization)
#             mask_rgba[:, :, 1] = binmask  # G: white where pink
#             mask_rgba[:, :, 2] = binmask  # B: white where pink
#             # Alpha: invert so pink areas get alpha=0 → will become white after 255-alpha
#             mask_rgba[:, :, 3] = 255 - binmask
            
#             log.info("Successfully created binary mask: %d pink pixels → white (255), %d pixels → black (0)",
#                      nonzero, binmask.shape[0] * binmask.shape[1] - nonzero)
#         else:
#             mask_rgba = _load_rgba_mask_from_image(m)

#         # When mask_is_painted=true, we encode pink as alpha=0, so process_inpaint's default invert_mask=True works correctly
#         actual_invert = invert_mask  # Use default True for painted masks
#         log.info("Using invert_mask=%s (mask_is_painted=%s)", actual_invert, mask_is_painted)
        
#         result = process_inpaint(
#             np.array(img),
#             mask_rgba,
#             invert_mask=actual_invert,
#             prompt=prompt,
#         )
#         result_name = f"output_{uuid.uuid4().hex}.png"
#         result_path = os.path.join(OUTPUT_DIR, result_name)
#         Image.fromarray(result).save(result_path, "PNG", optimize=False, compress_level=1)

#         url: Optional[str] = None
#         try:
#             if request is not None:
#                 url = str(request.url_for("download_file", filename=result_name))
#         except Exception:
#             url = None

#         entry: Dict[str, str] = {"result": result_name, "timestamp": datetime.utcnow().isoformat()}
#         if url:
#             entry["url"] = url
#         logs.append(entry)
#         resp: Dict[str, str] = {"result": result_name}
#         if url:
#             resp["url"] = url
#         log_media_click(user_id, final_category_id, appname)
#         return resp
#     except Exception as e:
#         status = "fail"
#         error_msg = str(e)
#         raise
#     finally:
#         # Always log to regular MongoDB (mandatory)
#         end_time = time.time()
#         response_time_ms = (end_time - start_time) * 1000
#         log_doc = {
#             "endpoint": "inpaint-multipart",
#             "output_id": result_name,
#             "status": status,
#             "timestamp": datetime.utcnow(),
#             "ts": int(time.time()),
#             "response_time_ms": response_time_ms,
#         }
#         # Store appname in api_logs if provided
#         if appname:
#             log_doc["appname"] = appname
#         if error_msg:
#             log_doc["error"] = error_msg
#         if mongo_logs is not None:
#             try:
#                 log.info("Inserting log to MongoDB - Database: %s, Collection: %s", mongo_logs.database.name, mongo_logs.name)
#                 result = mongo_logs.insert_one(log_doc)
#                 log.info("Mongo log inserted successfully: _id=%s, output_id=%s, status=%s, db=%s, collection=%s", 
#                         result.inserted_id, output_name, status, mongo_logs.database.name, mongo_logs.name)
                
#                 # Verify the insert by reading it back
#                 try:
#                     verify_doc = mongo_logs.find_one({"_id": result.inserted_id})
#                     if verify_doc:
#                         log.info("Verified: Document exists in MongoDB after insert")
#                     else:
#                         log.error("WARNING: Document not found after insert! _id=%s", result.inserted_id)
#                 except Exception as verify_err:
#                     log.warning("Could not verify insert: %s", verify_err)
#             except Exception as mongo_err:
#                 log.error("Mongo log insert failed: %s, log_doc=%s", mongo_err, log_doc, exc_info=True)
#         else:
#             log.warning("MongoDB not configured, skipping log insert")


# @app.post("/remove-pink")
# def remove_pink_segments(
#     image: UploadFile = File(...),
#     request: Request = None,
#     user_id: Optional[str] = Form(None),
#     category_id: Optional[str] = Form(None),
#     appname: Optional[str] = Form(None),
#     _: None = Depends(bearer_auth),
# ) -> Dict[str, str]:
#     """
#     Simple endpoint: upload an image with pink/magenta segments to remove.
#     - Pink/Magenta segments → automatically removed (white in mask)
#     - Everything else → automatically kept (black in mask)
#     Just paint pink/magenta on areas you want to remove, upload the image, and it works!
#     """
#     start_time = time.time()
#     status = "success"
#     error_msg = None
#     result_name = None
    
#     try:
#         # Handle appname="collage-maker": get category_id from collage-maker if not provided
#         final_category_id = category_id
#         if appname == "collage-maker" and not final_category_id:
#             final_category_id = get_category_id_from_collage_maker()
#             if final_category_id:
#                 log.info("Using category_id from collage-maker: %s", final_category_id)
        
#         log.info(f"Simple remove-pink: processing image {image.filename}")
        
#         # Load the image (with pink paint on it)
#         img = Image.open(image.file).convert("RGBA")
#         img_rgb = cv2.cvtColor(np.array(img), cv2.COLOR_RGBA2RGB)
        
#         # Auto-detect pink/magenta segments to remove
#         # Pink/Magenta → white in mask (remove)
#         # Everything else (natural image colors, including dark areas) → black in mask (keep)
        
#         # Detect pink/magenta using fixed RGB bounds per requested logic
#         lower = np.array([150, 0, 100], dtype=np.uint8)
#         upper = np.array([255, 120, 255], dtype=np.uint8)
#         binmask = (
#             (img_rgb[:, :, 0] >= lower[0]) & (img_rgb[:, :, 0] <= upper[0]) &
#             (img_rgb[:, :, 1] >= lower[1]) & (img_rgb[:, :, 1] <= upper[1]) &
#             (img_rgb[:, :, 2] >= lower[2]) & (img_rgb[:, :, 2] <= upper[2])
#         ).astype(np.uint8) * 255
        
#         # Clean up the pink mask
#         kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
#         binmask = cv2.morphologyEx(binmask, cv2.MORPH_CLOSE, kernel, iterations=2)
#         binmask = cv2.morphologyEx(binmask, cv2.MORPH_OPEN, kernel, iterations=1)
        
#         nonzero = int((binmask > 0).sum())
#         total_pixels = binmask.shape[0] * binmask.shape[1]
#         log.info(f"Detected {nonzero} pink pixels ({100*nonzero/total_pixels:.2f}% of image) to remove")
        
#         # Debug: log bounds used
#         log.info("Pink detection bounds used: lower=[150,0,100], upper=[255,120,255]")
        
#         if nonzero < 50:
#             log.error("No pink segments detected! Returning original image.")
#             result = np.array(img.convert("RGB"))
#             result_name = f"output_{uuid.uuid4().hex}.png"
#             result_path = os.path.join(OUTPUT_DIR, result_name)
#             Image.fromarray(result).save(result_path, "PNG", optimize=False, compress_level=1)
#             return {
#                 "result": result_name,
#                 "error": "No pink/magenta segments detected. Please paint areas to remove with magenta/pink color (RGB 255,0,255)."
#             }
        
#         # Create binary mask: Pink pixels → white (255), Everything else → black (0)
#         # Encode in RGBA format that process_inpaint expects
#         # process_inpaint does: mask = 255 - mask[:,:,3]
#         # So: alpha=0 (transparent/pink) → becomes 255 (white/remove)
#         #     alpha=255 (opaque/keep) → becomes 0 (black/keep)
#         mask_rgba = np.zeros((binmask.shape[0], binmask.shape[1], 4), dtype=np.uint8)
#         # RGB channels don't matter for process_inpaint, but set them to white where pink for visualization
#         mask_rgba[:, :, 0] = binmask  # R: white where pink
#         mask_rgba[:, :, 1] = binmask  # G: white where pink  
#         mask_rgba[:, :, 2] = binmask  # B: white where pink
#         # Alpha: 0 (transparent) where pink → will become white after 255-alpha
#         #        255 (opaque) everywhere else → will become black after 255-alpha
#         mask_rgba[:, :, 3] = 255 - binmask  # Invert: pink areas get alpha=0, rest get alpha=255
        
#         # Verify mask encoding
#         alpha_zero_count = int((mask_rgba[:,:,3] == 0).sum())
#         alpha_255_count = int((mask_rgba[:,:,3] == 255).sum())
#         total_pixels = binmask.shape[0] * binmask.shape[1]
#         log.info(f"Mask encoding: {alpha_zero_count} pixels with alpha=0 (pink), {alpha_255_count} pixels with alpha=255 (keep)")
#         log.info(f"After 255-alpha conversion: {alpha_zero_count} will become white (255/remove), {alpha_255_count} will become black (0/keep)")
        
#         # IMPORTANT: We need to use the ORIGINAL image WITHOUT pink paint for inpainting!
#         # Remove pink from the original image before processing
#         # Create a clean version: where pink was detected, keep original image colors
#         img_clean = np.array(img.convert("RGBA"))
#         # Where pink is detected, we want to inpaint, so we can leave it (or blend it out)
#         # Actually, the model will inpaint over those areas, so we can pass the original
#         # But for better results, we might want to remove the pink overlay first
        
#         # Process with invert_mask=True (default) because process_inpaint expects alpha=0 for removal
#         log.info(f"Starting inpainting process...")
#         result = process_inpaint(img_clean, mask_rgba, invert_mask=True)
#         log.info(f"Inpainting complete, result shape: {result.shape}")
#         result_name = f"output_{uuid.uuid4().hex}.png"
#         result_path = os.path.join(OUTPUT_DIR, result_name)
#         Image.fromarray(result).save(result_path, "PNG", optimize=False, compress_level=1)
        
#         url: Optional[str] = None
#         try:
#             if request is not None:
#                 url = str(request.url_for("download_file", filename=result_name))
#         except Exception:
#             url = None
        
#         logs.append({
#             "result": result_name,
#             "filename": image.filename,
#             "pink_pixels": nonzero,
#             "timestamp": datetime.utcnow().isoformat()
#         })
        
#         resp: Dict[str, str] = {"result": result_name, "pink_segments_detected": str(nonzero)}
#         if url:
#             resp["url"] = url
#         log_media_click(user_id, final_category_id, appname)
#         return resp
#     except Exception as e:
#         status = "fail"
#         error_msg = str(e)
#         raise
#     finally:
#         # Always log to regular MongoDB (mandatory)
#         end_time = time.time()
#         response_time_ms = (end_time - start_time) * 1000
#         log_doc = {
#             "endpoint": "remove-pink",
#             "output_id": result_name,
#             "status": status,
#             "timestamp": datetime.utcnow(),
#             "ts": int(time.time()),
#             "response_time_ms": response_time_ms,
#         }
#         # Store appname in api_logs if provided
#         if appname:
#             log_doc["appname"] = appname
#         if error_msg:
#             log_doc["error"] = error_msg
#         if mongo_logs is not None:
#             try:
#                 log.info("Inserting log to MongoDB - Database: %s, Collection: %s", mongo_logs.database.name, mongo_logs.name)
#                 result = mongo_logs.insert_one(log_doc)
#                 log.info("Mongo log inserted successfully: _id=%s, output_id=%s, status=%s, db=%s, collection=%s", 
#                         result.inserted_id, output_name, status, mongo_logs.database.name, mongo_logs.name)
                
#                 # Verify the insert by reading it back
#                 try:
#                     verify_doc = mongo_logs.find_one({"_id": result.inserted_id})
#                     if verify_doc:
#                         log.info("Verified: Document exists in MongoDB after insert")
#                     else:
#                         log.error("WARNING: Document not found after insert! _id=%s", result.inserted_id)
#                 except Exception as verify_err:
#                     log.warning("Could not verify insert: %s", verify_err)
#             except Exception as mongo_err:
#                 log.error("Mongo log insert failed: %s, log_doc=%s", mongo_err, log_doc, exc_info=True)
#         else:
#             log.warning("MongoDB not configured, skipping log insert")


# @app.get("/download/{filename}")
# def download_file(filename: str):
#     path = os.path.join(OUTPUT_DIR, filename)
#     if not os.path.isfile(path):
#         raise HTTPException(status_code=404, detail="file not found")
#     return FileResponse(path)


# @app.get("/result/{filename}")
# def view_result(filename: str):
#     """View result image directly in browser (same as download but with proper content-type for viewing)"""
#     path = os.path.join(OUTPUT_DIR, filename)
#     if not os.path.isfile(path):
#         raise HTTPException(status_code=404, detail="file not found")
#     return FileResponse(path, media_type="image/png")


# @app.get("/logs")
# def get_logs(_: None = Depends(bearer_auth)) -> JSONResponse:
#     return JSONResponse(content=logs)