File size: 150,745 Bytes
a74b879
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
import os
import json
from fastapi import FastAPI, Request, BackgroundTasks
from fastapi.responses import FileResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from pathlib import Path
import datetime
import sqlite3
from typing import Optional, List

from dotenv import load_dotenv
load_dotenv(override=True)

from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.util import get_remote_address
from slowapi.errors import RateLimitExceeded

print(" GEO Platform API starting...")
print(f" Working directory: {os.getcwd()}")
print(f" Python version: {os.sys.version}")

# lazily import heavy pipeline to avoid startup failures when optional deps
# (like spaCy) are not installed. import inside handlers that need it.
run_pipeline = None

try:
    from server import ai_analysis
    print("  ai_analysis loaded (from server)")
except Exception as e:
    print(f" ai_analysis failed: {e}")
    ai_analysis = None

try:
    from server import geo_services
    print("  geo_services loaded")
except Exception as e:
    print(f"  geo_services failed: {e}")
    geo_services = None

try:
    from server import ai_visibility
    print("  ai_visibility loaded")
except Exception as e:
    print(f"  ai_visibility failed: {e}")
    ai_visibility = None

try:
    from server import job_queue
    print(" job_queue loaded")
except Exception as e:
    print(f" job_queue failed: {e}")
    job_queue = None

try:
    from server import keyword_engine
    print(" keyword_engine loaded")
except Exception as e:
    print(f"  keyword_engine failed: {e}")
    keyword_engine = None

try:
    from server import users as user_mgmt
    print(" users loaded")
except Exception as e:
    print(f" users failed: {e}")
    user_mgmt = None

try:
    from server import search_intel
    print(" search_intel loaded")
except Exception as e:
    print(f" search_intel failed: {e}")
    search_intel = None

try:
    from server import payments as _payments
except Exception:
    _payments = None

try:
    from server import onboarding
except Exception:
    onboarding = None

from fastapi import WebSocket
import asyncio

OUTPUT_DIR = Path(os.environ.get('OUTPUT_DIR', str(Path(__file__).resolve().parent.parent / 'output')))
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)

print(f" Output directory: {OUTPUT_DIR}")

app = FastAPI(title='GEO Platform API')

# CORS middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=['*'],
    allow_credentials=True,
    allow_methods=['*'],
    allow_headers=['*'],
)

# Rate limiting
limiter = Limiter(key_func=get_remote_address)
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)

print(" FastAPI app created with rate limiting and CORS")

# Serve frontend static files
frontend_dir = Path(__file__).resolve().parent.parent / 'frontend'
if frontend_dir.exists():
    app.mount('/static', StaticFiles(directory=str(frontend_dir)), name='static')
    print(f" Frontend mounted: {frontend_dir}")
else:
    print(f" Frontend directory not found: {frontend_dir}")

class CrawlRequest(BaseModel):
    url: str
    org_name: str
    org_url: str
    max_pages: int = 3
    runs: int = 1
    api_keys: Optional[dict] = None

class RecommendationRequest(BaseModel):
    api_keys: Optional[dict] = None
    job_id: Optional[int] = None
    extra_context: Optional[dict] = None

class AnalysisRequest(BaseModel):
    api_keys: Optional[dict] = None
    job_id: Optional[int] = None

class SimulationRequest(BaseModel):
    content: str
    brand: str
    api_keys: Optional[dict] = None

@app.post('/api/crawl')
async def api_crawl(req: CrawlRequest):
    global run_pipeline
    if run_pipeline is None:
        try:
            from src.main import run_pipeline as _rp
            run_pipeline = _rp
        except Exception as e:
            return JSONResponse({'ok': False, 'error': 'pipeline not available: ' + str(e)}, status_code=500)
    # runs: perform multiple runs and average scores, snapshot first run
    runs = max(1, req.runs or 1)
    run_results = []
    timestamps = []
    scores = []
    breakdowns = []
    audit_objs = []
    try:
        for i in range(runs):
            ts = datetime.datetime.utcnow().strftime('%Y%m%dT%H%M%SZ')
            subdir = OUTPUT_DIR / f"run-{ts}-{i+1}"
            res = run_pipeline(req.url, req.org_name, req.org_url, max_pages=req.max_pages, output_dir=subdir)
            # load created audit
            audit_path = Path(res['audit_path'])
            with open(audit_path, 'r', encoding='utf-8') as f:
                audit_obj = json.load(f)
            audit_objs.append(audit_obj)

            # Infer brand name if generic for visibility check
            org_name_for_visibility = req.org_name
            if not org_name_for_visibility or org_name_for_visibility == 'Company':
                pages_for_inference = audit_obj.get('pages', [])
                inferred = ai_analysis.infer_brand_name(pages_for_inference)
                if inferred and inferred != 'Company':
                    org_name_for_visibility = inferred
                    # Update audit_obj with inferred name for consistency
                    audit_obj['org_name'] = inferred
            
            # run AI visibility (Perplexity) for this run and attach; fallback to OpenAI visibility
            queries = [f"What is {org_name_for_visibility}?", f"Best services for {org_name_for_visibility}", f"Why should I buy from {org_name_for_visibility}?"]
            perf = ai_visibility.check_perplexity(org_name_for_visibility, queries)
            if not perf.get('enabled') and perf.get('reason') == 'PERPLEXITY_KEY not set':
                # try OpenAI fallback
                try:
                    perf = ai_visibility.check_openai_visibility(org_name_for_visibility, queries)
                    perf['fallback'] = 'openai'
                except Exception:
                    pass
            
            # ๐Ÿ”ท ADDED: Deep Sentiment & Context Analysis (The "Zaher" Gap)
            try:
                sentiment = geo_services.sentiment_analysis(org_name_for_visibility, queries, api_keys=req.api_keys)
                perf['sentiment_analysis'] = sentiment
            except Exception:
                pass

            audit_obj['ai_visibility'] = perf
            # overwrite audit with ai visibility included
            with open(audit_path, 'w', encoding='utf-8') as f:
                json.dump(audit_obj, f, ensure_ascii=False, indent=2)

            # compute geo score for this run
            score = ai_analysis.compute_geo_score(audit_obj.get('pages', []), audit=audit_obj, ai_visibility=perf)
            scores.append(score['score'])
            breakdowns.append(score['breakdown'])
            run_results.append({ 'ts': ts, 'audit_path': str(audit_path), 'geo_score': score })
            timestamps.append(ts)

        # snapshot first run pages for deterministic reference
        snap_ts = timestamps[0]
        snap_src = Path(run_results[0]['audit_path'])
        snap_dst = OUTPUT_DIR / f"snapshot-{snap_ts}.json"
        with open(snap_src, 'r', encoding='utf-8') as fsrc, open(snap_dst, 'w', encoding='utf-8') as fdst:
            fdst.write(fsrc.read())

        # Update the main audit/analysis files so UI endpoints (`/api/results`) read latest data
        try:
            # copy snapshot to output/audit.json
            audit_main = OUTPUT_DIR / 'audit.json'
            with open(snap_dst, 'r', encoding='utf-8') as s, open(audit_main, 'w', encoding='utf-8') as m:
                m.write(s.read())

            # generate and save aggregated analysis (OpenAI/Groq) and geo_score based on snapshot
            try:
                with open(audit_main, 'r', encoding='utf-8') as f:
                    audit_obj = json.load(f)
                pages = audit_obj.get('pages', [])
                analysis = ai_analysis.analyze_pages(pages)
                geo_score = ai_analysis.compute_geo_score(pages, audit=audit_obj, ai_visibility=audit_obj.get('ai_visibility'))
                analysis_out = { 'analysis': analysis, 'geo_score': geo_score }
                with open(OUTPUT_DIR / 'analysis.json', 'w', encoding='utf-8') as fa:
                    json.dump(analysis_out, fa, ensure_ascii=False, indent=2)
                # also save a top-level analysis.json for backwards compatibility
            except Exception:
                pass
        except Exception:
            pass

        # compute aggregated stats
        import statistics
        mean_score = int(round(statistics.mean(scores)))
        median_score = int(round(statistics.median(scores)))
        variance = float(statistics.pstdev(scores))

        history_path = OUTPUT_DIR / 'history.json'
        history = []
        if history_path.exists():
            try:
                history = json.loads(history_path.read_text(encoding='utf-8'))
            except Exception:
                history = []
        entry = {
            'timestamp': timestamps[0],
            'url': req.url,
            'org_name': req.org_name,
            'runs': runs,
            'scores': scores,
            'mean': mean_score,
            'median': median_score,
            'variance': variance,
            'runs_info': run_results
        }
        history.append(entry)
        history_path.write_text(json.dumps(history, ensure_ascii=False, indent=2), encoding='utf-8')

        return { 'ok': True, 'message': 'crawl completed', 'mean_score': mean_score, 'median_score': median_score, 'variance': variance, 'history_entry': entry }
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


class JobRequest(BaseModel):
    url: str
    org_name: str
    org_url: str
    max_pages: int = 3
    runs: int = 1
    industry_override: Optional[str] = None


@app.post('/api/jobs')
# @limiter.limit("30/minute")  # Rate limiting disabled for testing
async def api_enqueue(job: JobRequest, background_tasks: BackgroundTasks, request: Request):
    try:
        # โ”€โ”€ Usage limit check โ”€โ”€ TEMPORARILY DISABLED FOR DEVELOPMENT
        user_id = None
        try:
            auth = request.headers.get('authorization', '')
            token = auth.split(' ', 1)[1].strip()
            user_id = user_mgmt.verify_token(token)
        except Exception:
            pass

        # TEMPORARILY DISABLED: Allow unlimited access during development
        # TODO: Re-enable usage limits later
        # if user_id:
        #     # Check trial limit first
        #     if onboarding:
        #         trial_status = onboarding.get_trial_status(user_id)
        #         subscription = _payments.get_subscription(user_id)
        #         
        #         # If on free plan and trial expired, show pricing
        #         if subscription.get('plan') == 'free' and trial_status['trial_expired']:
        #             return JSONResponse({
        #                 'ok': False,
        #                 'error': 'ุงู†ุชู‡ุช ูุชุฑุฉ ุงู„ุชุฌุฑุจุฉ ุงู„ู…ุฌุงู†ูŠุฉ. ูŠุฑุฌู‰ ุงู„ุชุฑู‚ูŠุฉ ุฅู„ู‰ ุฎุทุฉ ู…ุฏููˆุนุฉ.',
        #                 'trial_expired': True,
        #                 'show_pricing': True,
        #                 'plan': 'free'
        #             }, status_code=429)
        #         
        #         # Check if free user has used their one try
        #         if subscription.get('plan') == 'free' and trial_status['tries_remaining'] <= 0:
        #             return JSONResponse({
        #                 'ok': False,
        #                 'error': 'ู„ู‚ุฏ ุงุณุชุฎุฏู…ุช ู…ุญุงูˆู„ุชูƒ ุงู„ู…ุฌุงู†ูŠุฉ. ูŠุฑุฌู‰ ุงู„ุชุฑู‚ูŠุฉ ู„ู„ุญุตูˆู„ ุนู„ู‰ ุงู„ู…ุฒูŠุฏ ู…ู† ุงู„ุชุญู„ูŠู„ุงุช.',
        #                 'trial_exhausted': True,
        #                 'show_pricing': True,
        #                 'plan': 'free',
        #                 'tries_used': trial_status['tries_used']
        #             }, status_code=429)
        #     
        #     limit_check = _payments.check_usage_limit(user_id, 'crawls')
        #     if not limit_check['allowed']:
        #         plan = _payments.get_subscription(user_id).get('plan', 'free')
        #         return JSONResponse({
        #             'ok': False,
        #             'error': f'ู„ู‚ุฏ ุงุณุชู†ูุฏุช ุญุฏ ุงู„ุชุญู„ูŠู„ุงุช ุงู„ุดู‡ุฑูŠ ({limit_check["limit"]} ุชุญู„ูŠู„). ูŠุฑุฌู‰ ุงู„ุชุฑู‚ูŠุฉ ุฅู„ู‰ ุฎุทุฉ ุฃุนู„ู‰.',
        #             'limit_reached': True,
        #             'plan': plan,
        #             'used': limit_check['used'],
        #             'limit': limit_check['limit']
        #         }, status_code=429)
        
        jid = job_queue.enqueue_job(
            job.url, 
            job.org_name, 
            job.org_url, 
            job.max_pages, 
            job.runs,
            industry_override=job.industry_override
        )
        
        # Track usage - TEMPORARILY DISABLED
        # TODO: Re-enable usage tracking later
        # if user_id:
        #     try:
        #         _payments.track_usage(user_id, 'crawls')
        #         # Use trial attempt for free users
        #         if onboarding:
        #             subscription = _payments.get_subscription(user_id)
        #             if subscription.get('plan') == 'free':
        #                 onboarding.use_trial(user_id)
        #     except Exception:
        #         pass
        
        # Dispatch background task immediately
        from server.worker import process_job
        job_data = job_queue.get_job(jid)
        if job_data:
            background_tasks.add_task(process_job, job_data)
            
        return {'ok': True, 'job_id': jid}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


@app.get('/api/jobs')
async def api_list_jobs():
    try:
        data = job_queue.list_jobs()
        return {'ok': True, 'jobs': data}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


@app.get('/api/jobs/{job_id}')
async def api_get_job(job_id: int):
    try:
        job = job_queue.get_job(job_id)
        if not job:
            return JSONResponse({'ok': False, 'error': 'not found'}, status_code=404)
        # parse progress JSON
        try:
            job['progress'] = json.loads(job.get('progress') or '{}')
        except Exception:
            job['progress'] = {}
        return {'ok': True, 'job': job}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


@app.websocket('/ws/jobs/{job_id}')
async def ws_job_progress(ws: WebSocket, job_id: int):
    await ws.accept()
    last_updated = None
    try:
        while True:
            job = job_queue.get_job(job_id)
            if not job:
                # send a not-found once then keep waiting in case job appears
                try:
                    await ws.send_json({'ok': False, 'error': 'job not found'})
                except Exception:
                    pass
                await asyncio.sleep(1)
                continue

            # normalize progress and datetime fields for JSON
            try:
                prog = job.get('progress')
                if isinstance(prog, str):
                    try:
                        job['progress'] = json.loads(prog or '{}')
                    except Exception:
                        job['progress'] = {}
                else:
                    job['progress'] = prog or {}
            except Exception:
                job['progress'] = {}

            # convert timestamps to ISO strings
            for dt_key in ('created_at', 'updated_at'):
                try:
                    val = job.get(dt_key)
                    if hasattr(val, 'isoformat'):
                        job[dt_key] = val.isoformat()
                    else:
                        job[dt_key] = str(val) if val is not None else None
                except Exception:
                    job[dt_key] = str(job.get(dt_key))

            updated = job.get('updated_at')
            if updated != last_updated:
                last_updated = updated
                try:
                    await ws.send_json({'ok': True, 'job': job})
                except Exception:
                    # if sending fails (e.g., client gone), break loop
                    break
            await asyncio.sleep(1)
    finally:
        try:
            await ws.close()
        except Exception:
            pass

@app.get('/api/jobs/{job_id}/results')
async def api_job_results(job_id: int):
    job = job_queue.get_job(job_id)
    if not job:
        return JSONResponse({'ok': False, 'error': 'not found'}, status_code=404)
    result_path = job.get('result_path')
    if not result_path:
        return JSONResponse({'ok': False, 'error': 'no results yet'}, status_code=400)
    out = {'ok': True, 'job_id': job_id}
    audit_path = Path(result_path) / 'audit.json'
    analysis_path = Path(result_path) / 'analysis.json'
    schema_path = Path(result_path) / 'schema.jsonld'
    if audit_path.exists():
        out['audit'] = json.loads(audit_path.read_text(encoding='utf-8'))
    if analysis_path.exists():
        out['analysis'] = json.loads(analysis_path.read_text(encoding='utf-8'))
    if schema_path.exists():
        out['schema'] = schema_path.read_text(encoding='utf-8')
    return out


@app.get('/api/results')
async def api_results(ts: str | None = None):
    from server.cache_manager import invalidate_results_cache
    
    if ts:
        snapshot_path = OUTPUT_DIR / f'snapshot-{ts}.json'
        if snapshot_path.exists():
            try:
                result = {'audit': json.loads(snapshot_path.read_text(encoding='utf-8'))}
                return JSONResponse(result, headers={"Cache-Control": "no-store, no-cache, must-revalidate, max-age=0"})
            except Exception as e:
                return JSONResponse({'ok': False, 'error': f'Failed to load snapshot: {str(e)}'}, status_code=500)
    
    audit_path = OUTPUT_DIR / 'audit.json'
    schema_path = OUTPUT_DIR / 'schema.jsonld'
    out = {}
    if audit_path.exists():
        out['audit'] = json.loads(audit_path.read_text(encoding='utf-8'))
    if schema_path.exists():
        out['schema'] = schema_path.read_text(encoding='utf-8')
    return JSONResponse(out, headers={"Cache-Control": "no-store, no-cache, must-revalidate, max-age=0"})

@app.on_event("startup")
async def startup_event():
    print(" GEO Platform API is ready!")
    print(f" Access at: http://0.0.0.0:7860")
    print(f" Health check: http://0.0.0.0:7860/health")
    try:
        admin_email = os.environ.get('ADMIN_EMAIL', 'admin@moharek.com')
        admin_pass = os.environ.get('ADMIN_PASSWORD', 'moharek2025')
        users = user_mgmt.list_users()
        if not any(u.get('email') == admin_email for u in users):
            uid = user_mgmt.create_user(
                email=admin_email,
                password=admin_pass,
                role='admin'
            )
            print(f" Seeded default admin user (id={uid})")
    except Exception as e:
        print(f" Seed user error: {e}")

@app.get('/api/health')
@app.get('/health')
async def health_check():
    return {'status': 'healthy', 'service': 'GEO Platform'}

@app.get('/')
async def index():
    index_file = frontend_dir / 'index.html'
    if index_file.exists():
        return FileResponse(str(index_file), headers={"Cache-Control": "no-store, no-cache, must-revalidate, max-age=0"})
    return {'ok': True}

@app.get('/{file_path:path}', include_in_schema=False)
async def serve_static(file_path: str):
    """Serve static files including SVG, CSS, JS, etc."""
    if file_path.startswith('api/'):
        return JSONResponse({'ok': False, 'error': 'not found'}, status_code=404)
    
    file_full_path = frontend_dir / file_path
    
    try:
        file_full_path = file_full_path.resolve()
        if not str(file_full_path).startswith(str(frontend_dir.resolve())):
            return JSONResponse({'ok': False, 'error': 'forbidden'}, status_code=403)
    except Exception:
        return JSONResponse({'ok': False, 'error': 'invalid path'}, status_code=400)
    
    if file_full_path.exists() and file_full_path.is_file():
        media_type = 'application/octet-stream'
        if file_path.endswith('.svg'):
            media_type = 'image/svg+xml'
        elif file_path.endswith('.css'):
            media_type = 'text/css'
        elif file_path.endswith('.js'):
            media_type = 'application/javascript'
        elif file_path.endswith('.html'):
            media_type = 'text/html'
        elif file_path.endswith('.json'):
            media_type = 'application/json'
        elif file_path.endswith('.png'):
            media_type = 'image/png'
        elif file_path.endswith('.jpg') or file_path.endswith('.jpeg'):
            media_type = 'image/jpeg'
        elif file_path.endswith('.gif'):
            media_type = 'image/gif'
        elif file_path.endswith('.webp'):
            media_type = 'image/webp'
        
        return FileResponse(str(file_full_path), media_type=media_type, headers={"Cache-Control": "public, max-age=3600"})
    
    if not file_path.endswith('.html'):
        html_path = frontend_dir / f'{file_path}.html'
        if html_path.exists():
            return FileResponse(str(html_path), media_type='text/html', headers={"Cache-Control": "no-store, no-cache, must-revalidate, max-age=0"})
    
    return JSONResponse({'ok': False, 'error': 'not found'}, status_code=404)





@app.get('/api/jobs/{job_id}/report')
async def api_job_report(job_id: int):
    job = job_queue.get_job(job_id)
    if not job:
        return JSONResponse({'ok': False, 'error': 'job not found'}, status_code=404)
    result_path = job.get('result_path')
    if not result_path:
        return JSONResponse({'ok': False, 'error': 'job result not ready'}, status_code=400)
    from server import reports
    html = reports.build_html_report(result_path)
    return JSONResponse({'ok': True, 'report_html': html})


@app.get('/api/jobs/{job_id}/report.pdf')
async def api_job_report_pdf(job_id: int):
    job = job_queue.get_job(job_id)
    if not job:
        return JSONResponse({'ok': False, 'error': 'job not found'}, status_code=404)
    result_path = job.get('result_path')
    if not result_path:
        return JSONResponse({'ok': False, 'error': 'job result not ready'}, status_code=400)
    try:
        from server import reports
        html = reports.build_html_report(result_path)
        out_pdf = Path(result_path) / f'report-{job_id}.pdf'
        ok = reports.try_render_pdf(html, out_pdf)
        if ok and out_pdf.exists():
            return FileResponse(str(out_pdf), media_type='application/pdf', filename=f'report-{job_id}.pdf')
    except Exception as e:
        print(f'PDF generation error: {e}')
    return JSONResponse({'ok': False, 'error': 'pdf_generation_failed'}, status_code=500)


@app.get('/api/jobs/{job_id}/keywords')
async def api_job_keywords(job_id: int, enrich: bool = False, analytics: bool = False):
    try:
        job = job_queue.get_job(job_id)
        if not job:
            return JSONResponse({'ok': False, 'error': 'job not found'}, status_code=404)
        result_path = job.get('result_path')
        if not result_path:
            return JSONResponse({'ok': False, 'error': 'job result not ready'}, status_code=400)
        audit_path = Path(result_path) / 'audit.json'
        if not audit_path.exists():
            return JSONResponse({'ok': False, 'error': 'audit.json not found in result_path'}, status_code=404)
        with open(audit_path, 'r', encoding='utf-8') as f:
            audit = json.load(f)
        result = keyword_engine.extract_keywords_from_audit(audit, top_n=40, enrich=enrich, analytics=analytics)
        
        if analytics:
            return {'ok': True, 'analytics': result}
        else:
            return {'ok': True, 'keywords': result}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


@app.get('/api/jobs/{job_id}/serp')
async def api_job_serp(job_id: int, gl: str = 'sa', hl: str = 'ar'):
    """Full SERP report via ScrapingBee (rank check, PAA, local, competitors)."""
    try:
        from server import scrapingbee_client
        job = job_queue.get_job(job_id)
        if not job:
            return JSONResponse({'ok': False, 'error': 'job not found'}, status_code=404)
        result_path = job.get('result_path')
        if not result_path:
            return JSONResponse({'ok': False, 'error': 'job result not ready'}, status_code=400)
        audit_path = Path(result_path) / 'audit.json'
        if not audit_path.exists():
            return JSONResponse({'ok': False, 'error': 'audit.json not found'}, status_code=404)
        with open(audit_path, 'r', encoding='utf-8') as f:
            audit = json.load(f)
        site_url = job.get('url', '')
        kws_raw = keyword_engine.extract_keywords_from_audit(audit, top_n=8)
        keywords = [k['kw'] if isinstance(k, dict) else k for k in kws_raw[:8]]
        report = scrapingbee_client.full_serp_report(site_url, keywords, country_code=gl, language=hl)
        return report
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


@app.get('/api/jobs/{job_id}/actions')
async def api_job_actions(job_id: int):
    try:
        job = job_queue.get_job(job_id)
        if not job:
            return JSONResponse({'ok': False, 'error': 'job not found'}, status_code=404)
        result_path = job.get('result_path')
        if not result_path:
            return JSONResponse({'ok': False, 'error': 'job result not ready'}, status_code=400)
        audit_path = Path(result_path) / 'audit.json'
        if not audit_path.exists():
            return JSONResponse({'ok': False, 'error': 'audit.json not found in result_path'}, status_code=404)
        with open(audit_path, 'r', encoding='utf-8') as f:
            audit = json.load(f)
        
        from server import action_engine
        actions = action_engine.generate_action_plan(audit)
        return actions
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


@app.post('/api/actions/save')
async def api_save_actions(request: Request):
    try:
        data = await request.json()
        job_id = data.get('job_id')
        actions = data.get('actions', [])
        
        from server.db import SessionLocal, Action
        db = SessionLocal()
        try:
            saved = []
            for act in actions:
                new_act = Action(
                    job_id=job_id,
                    type=act.get('type', 'general'),
                    task=act.get('task', ''),
                    priority_score=100 if str(act.get('priority')).lower() == 'high' else (50 if str(act.get('priority')).lower() == 'medium' else 10),
                    status='pending'
                )
                db.add(new_act)
                db.flush()
                saved.append(new_act.id)
            db.commit()
            return {'ok': True, 'saved_ids': saved}
        finally:
            db.close()
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


@app.get('/api/actions/list')
async def api_list_actions():
    try:
        from server.db import SessionLocal, Action
        db = SessionLocal()
        try:
            items = db.query(Action).order_by(Action.priority_score.desc()).limit(50).all()
            actions = []
            for i in items:
                action_dict = {
                    'id': i.id,
                    'job_id': i.job_id,
                    'type': i.type,
                    'task': i.task,
                    'priority_score': i.priority_score,
                    'status': i.status,
                    'result': i.result,
                    'created_at': str(i.created_at),
                    'impact': 'high' if i.priority_score >= 80 else 'medium' if i.priority_score >= 40 else 'low',
                    'effort': 'low',
                    'timeline': '1-2 ุงุณุงุจูŠุน'
                }
                if hasattr(i, 'initial_metrics') and i.initial_metrics:
                    action_dict['initial_metrics'] = i.initial_metrics
                if hasattr(i, 'latest_metrics') and i.latest_metrics:
                    action_dict['latest_metrics'] = i.latest_metrics
                if hasattr(i, 'impact_score') and i.impact_score:
                    action_dict['impact_score'] = i.impact_score
                actions.append(action_dict)
            return {'ok': True, 'actions': actions}
        finally:
            db.close()
    except Exception as e:
        import traceback
        traceback.print_exc()
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


@app.get('/api/mentions/list')
async def api_list_mentions():
    try:
        from server.db import SessionLocal, Mention
        db = SessionLocal()
        try:
            items = db.query(Mention).order_by(Mention.created_at.desc()).limit(50).all()
            return {'ok': True, 'mentions': [{
                'id': i.id, 'brand': i.brand, 'source': i.source,
                'content': i.content, 'url': i.url,
                'sentiment_score': i.sentiment_score, 'created_at': str(i.created_at)
            } for i in items]}
        finally:
            db.close()
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


@app.get('/api/graph/entities')
async def api_list_entities():
    try:
        from server.db import SessionLocal, Entity
        db = SessionLocal()
        try:
            items = db.query(Entity).order_by(Entity.roi_score.desc()).limit(100).all()
            return {'ok': True, 'entities': [{
                'id': i.id, 'name': i.name, 'type': i.type, 'roi_score': i.roi_score
            } for i in items]}
        finally:
            db.close()
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


@app.get('/api/ai_visibility/radar')
async def api_ai_radar(job_id: int):
    try:
        from server import ai_radar
        from server.db import SessionLocal, AIResponse, AIPrompt
        db = SessionLocal()
        try:
            responses = db.query(AIResponse).join(AIPrompt).filter(AIPrompt.job_id == job_id).order_by(AIResponse.created_at.desc()).limit(10).all()
            score = ai_radar.calculate_overall_visibility_score(job_id)
            return {
                'ok': True, 
                'overall_score': score,
                'latest_mentions': [{
                    'prompt': r.prompt_id, # Simplified
                    'mentioned': r.mention_found,
                    'model': r.model_name,
                    'competitors': r.competitors_mentioned
                } for r in responses]
            }
        finally:
            db.close()
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


@app.post('/api/autopilot/toggle')
async def api_toggle_autopilot(job_id: int, enabled: bool):
    try:
        from server.db import SessionLocal, ProjectSettings
        db = SessionLocal()
        try:
            settings = db.query(ProjectSettings).filter(ProjectSettings.job_id == job_id).first()
            if not settings:
                settings = ProjectSettings(job_id=job_id, autopilot_enabled=enabled)
                db.add(settings)
            else:
                settings.autopilot_enabled = enabled
            db.commit()
            return {'ok': True, 'autopilot_enabled': enabled}
        finally:
            db.close()
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


@app.get('/api/strategy/summary')
async def api_strategy_summary(job_id: int):
    try:
        from server import growth_os
        summary = growth_os.get_growth_strategy(job_id)
        return {'ok': True, 'summary': summary}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


@app.post('/api/actions/{action_id}/execute')
async def api_execute_action(action_id: int):
    try:
        from server import executor
        from server.db import SessionLocal, Action
        db = SessionLocal()
        try:
            act = db.query(Action).filter(Action.id == action_id).first()
            if act:
                executor.dispatch_action(action_id, act.type)
        finally:
            db.close()
        return {'ok': True, 'action_id': action_id, 'message': 'Dispatched successfully'}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


class UserRegister(BaseModel):
    email: str
    password: str
    company_id: int | None = None


class CompanyRegister(BaseModel):
    name: str
    domain: str | None = None


class LoginRequest(BaseModel):
    email: str
    password: str


@app.post('/api/companies/register')
async def api_register_company(req: CompanyRegister):
    try:
        cid = user_mgmt.create_company(req.name, req.domain)
        return {'ok': True, 'company_id': cid}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


@app.post('/api/users/register')
async def api_register_user(req: UserRegister):
    try:
        uid = user_mgmt.create_user(req.email, req.password, company_id=req.company_id)
        token = user_mgmt.make_token(uid)
        user = user_mgmt.get_user(uid)
        
        # Initialize trial and onboarding for new user
        if onboarding:
            onboarding.init_trial(uid)
            onboarding.init_onboarding(uid)
        
        return {'ok': True, 'user_id': uid, 'token': token, 'user': user}
    except sqlite3.IntegrityError:
        return JSONResponse({'ok': False, 'error': 'ุงู„ุจุฑูŠุฏ ุงู„ุฅู„ูƒุชุฑูˆู†ูŠ ู…ุณุฌู„ ุจุงู„ูุนู„'}, status_code=400)
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


@app.post('/api/users/login')
async def api_login(req: LoginRequest):
    try:
        user = user_mgmt.authenticate_user(req.email, req.password)
        if not user:
            return JSONResponse({'ok': False, 'error': 'invalid credentials'}, status_code=401)
        token = user_mgmt.make_token(user['id'])
        return {'ok': True, 'token': token, 'user': user}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


@app.get('/api/users/me')
async def api_me(request: Request):
    auth = request.headers.get('authorization') or request.headers.get('Authorization')
    if not auth or not auth.lower().startswith('bearer '):
        return JSONResponse({'ok': False, 'error': 'missing token'}, status_code=401)
    
    try:
        token = auth.split(' ', 1)[1].strip()
        if not token or len(token) < 10:
            return JSONResponse({'ok': False, 'error': 'invalid token'}, status_code=401)
        
        uid = user_mgmt.verify_token(token)
        if not uid:
            return JSONResponse({'ok': False, 'error': 'invalid token'}, status_code=401)
        
        u = user_mgmt.get_user(uid)
        if not u:
            return JSONResponse({'ok': False, 'error': 'user not found'}, status_code=404)
        
        return {'ok': True, 'user': u}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': 'token validation failed'}, status_code=401)


@app.post('/api/simulate')
async def api_simulate(req: SimulationRequest):
    try:
        prediction = ai_analysis.simulate_visibility(req.content, req.brand, api_keys=req.api_keys)
        return {'ok': True, 'prediction': prediction}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


@app.post('/api/analyze')
# @limiter.limit("20/minute")  # Rate limiting disabled for testing
async def api_analyze(req: AnalysisRequest = None, request: Request = None, job_id: int = None):
    api_keys = req.api_keys if req else {}
    job_id = job_id or (req.job_id if req else None)

    # Resolve audit path: job-specific first, then global fallback
    if job_id:
        job = job_queue.get_job(job_id)
        if not job:
            return JSONResponse({'ok': False, 'error': f'job {job_id} not found'}, status_code=404)
        result_path = job.get('result_path')
        if not result_path:
            return JSONResponse({'ok': False, 'error': f'Job {job_id} is still processing (result_path is empty). Please wait for the crawler to finish.'}, status_code=400)
        audit_path = Path(result_path) / 'audit.json'
        analysis_out_path = Path(result_path) / 'analysis.json'
    else:
        audit_path = OUTPUT_DIR / 'audit.json'
        analysis_out_path = OUTPUT_DIR / 'analysis.json'

    if not audit_path.exists():
        return JSONResponse({'ok': False, 'error': 'no audit found; run crawl first'}, status_code=400)

    with open(audit_path, 'r', encoding='utf-8') as f:
        audit = json.load(f)
    pages = audit.get('pages', [])
    
    # Pass user-provided keys to analysis
    analysis = ai_analysis.analyze_pages(pages, api_keys=api_keys)

    # AI Visibility Check (Optional Per-request override)
    ai_vis = audit.get('ai_visibility') or {}
    org_name = audit.get('org_name') or ai_analysis.infer_brand_name(pages)
    
    if api_keys:
        queries = [f"What is {org_name}?", f"Best services for {org_name}"]
        if api_keys.get('perplexity'):
            ai_vis = ai_visibility.check_perplexity(org_name, queries, api_key=api_keys.get('perplexity'))
        elif api_keys.get('openai'):
            ai_vis = ai_visibility.check_openai_visibility(org_name, queries, api_key=api_keys.get('openai'))

    # ๐Ÿ”ท Deep AI Visibility Analysis (Sentiment/Shopping/Context) - Always Run if possible
    try:
        deep_ai = ai_analysis.analyze_ai_visibility_deep(pages, org_name, api_keys=api_keys)
        # Flatten deep_ai into ai_vis so compute_geo_score can find them easily
        if deep_ai:
            ai_vis.update(deep_ai)
    except Exception as e:
        print(f"Deep AI analysis error: {e}")
        
    audit['ai_visibility'] = ai_vis
    # Save updated audit
    with open(audit_path, 'w', encoding='utf-8') as f:
        json.dump(audit, f, ensure_ascii=False, indent=2)

    from server import geo_services
    
    # โ”€โ”€ Enhanced Visibility Score v2 (API Based) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    org_name = audit.get('org_name') or ai_analysis.infer_brand_name(pages)
    
    # Fetch real search results using provided keys or environment fallbacks
    searches = []
    serp_key = (api_keys.get("SERPAPI_KEY") if api_keys else None) or os.getenv("SERPAPI_KEY")
    zen_key = (api_keys.get("ZENSERP_KEY") if api_keys else None) or os.getenv("ZENSERP_KEY")
    
    core_queries = [f"{org_name}", f"ุชุญู…ูŠู„ {org_name}", f"{org_name} review"]
    for cq in core_queries[:2]:
        s_res = geo_services._serp_api_search(cq, api_key=serp_key)
        if not s_res:
            s_res = geo_services._zenserp_search(cq, api_key=zen_key)
        if s_res:
            searches.append(s_res)

    # โ”€โ”€ Competitor Insight Enrichment โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    comp_insight = {}
    try:
        # Pass industry override if available
        industry_override = audit.get('industry_override')
        comp_insight = geo_services.get_competitor_insights(
            org_name, 
            audit.get('url'), 
            api_keys=api_keys,
            industry_override=industry_override
        )
    except Exception as e:
        print(f"Competitor insight error: {e}")
        pass

    # Hybrid Score Calculation (v2)
    ai_mentions = ai_vis.get("mentions", 0) if ai_vis else 0
    total_queries = ai_vis.get("total_queries", 1) if ai_vis else 1
    traffic_est = comp_insight.get("monthly_visits", "unknown")
    
    geo_v2 = geo_services.calculate_visibility_score_v2(
        org_name, searches, ai_mentions, total_queries, traffic_est
    )
    
    geo = ai_analysis.compute_geo_score(pages, audit=audit, ai_visibility=ai_vis)
    geo["v2"] = geo_v2 # Combined 40/40/20 score

    analysis_out = { 'analysis': analysis, 'geo_score': geo, 'competitor_insight': comp_insight }
    
    with open(analysis_out_path, 'w', encoding='utf-8') as fa:
        json.dump(analysis_out, fa, ensure_ascii=False, indent=2)

    return { 'ok': True, 'analysis': analysis, 'geo_score': geo, 'competitor_insight': comp_insight }


@app.get('/api/history')
async def api_history():
    history_path = OUTPUT_DIR / 'history.json'
    if not history_path.exists():
        return { 'ok': True, 'history': [] }
    try:
        data = json.loads(history_path.read_text(encoding='utf-8'))
        return { 'ok': True, 'history': data }
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


class ActivateRequest(BaseModel):
    ts: str
    api_keys: Optional[dict] = None


@app.post('/api/history/activate')
async def api_activate_history(req: ActivateRequest):
    """
    Switch the 'active' research to a historical snapshot.
    This overwrites audit.json and triggers a re-analysis.
    """
    try:
        ts = req.ts
        snapshot_path = OUTPUT_DIR / f'snapshot-{ts}.json'
        if not snapshot_path.exists():
            return JSONResponse({'ok': False, 'error': f'Snapshot {ts} not found'}, status_code=404)

        # 1. Update audit.json
        audit_main = OUTPUT_DIR / 'audit.json'
        with open(snapshot_path, 'r', encoding='utf-8') as s, open(audit_main, 'w', encoding='utf-8') as m:
            audit_obj = json.load(s)
            json.dump(audit_obj, m, ensure_ascii=False, indent=2)

        # 2. Trigger analysis and compute score
        pages = audit_obj.get('pages', [])
        api_keys = req.api_keys or {}
        
        # Pass user-provided keys to analysis
        analysis_data = ai_analysis.analyze_pages(pages, api_keys=api_keys)
        
        # If brand name is generic, infer it
        org_name = audit_obj.get('org_name', 'Company')
        if not org_name or org_name == 'Company':
            inferred = ai_analysis.infer_brand_name(pages)
            if inferred and inferred != 'Company':
                org_name = inferred
                audit_obj['org_name'] = org_name
                # Re-save with inferred name
                with open(audit_main, 'w', encoding='utf-8') as f:
                    json.dump(audit_obj, f, ensure_ascii=False, indent=2)

        ai_vis = audit_obj.get('ai_visibility')
        # Re-run visibility if keys provided
        if api_keys and (api_keys.get('perplexity') or api_keys.get('openai')):
            queries = [f"What is {org_name}?", f"Best services for {org_name}"]
            if api_keys.get('perplexity'):
                ai_vis = ai_visibility.check_perplexity(org_name, queries, api_key=api_keys['perplexity'])
            elif api_keys.get('openai'):
                ai_vis = ai_visibility.check_openai_visibility(org_name, queries, api_key=api_keys.get('openai'))
            audit_obj['ai_visibility'] = ai_vis
            with open(audit_main, 'w', encoding='utf-8') as f:
                json.dump(audit_obj, f, ensure_ascii=False, indent=2)

        geo_score = ai_analysis.compute_geo_score(pages, audit=audit_obj, ai_visibility=ai_vis)
        
        # 3. Save analysis.json
        full_report = { 'analysis': analysis_data, 'geo_score': geo_score }
        analysis_path = OUTPUT_DIR / 'analysis.json'
        with open(analysis_path, 'w', encoding='utf-8') as fa:
            json.dump(full_report, fa, ensure_ascii=False, indent=2)

        # 4. Generate Strategic Intelligence Report for the newly activated data
        # This ensures the Competitive Intelligence Matrix updates immediately
        try:
            from server import search_intelligence
            report = search_intelligence.run_complete_analysis(pages, source_url=audit_obj.get('url', 'http://example.com'), api_keys=api_keys)
        except Exception as e:
            print(f"Intelligence sync error: {e}")
            report = None

        return { 
            'ok': True, 
            'message': f'Research {ts} activated successfully',
            'org_name': org_name,
            'pages_count': len(pages),
            'report': report
        }
    except Exception as e:
        import traceback
        traceback.print_exc()
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


@app.post('/api/recommendations')
async def api_recommendations(req: RecommendationRequest = None):
    # load analysis and audit results then produce recommendations
    api_keys = req.api_keys if req else {}
    job_id = req.job_id if req else None
    extra_context = req.extra_context if (req and req.extra_context) else {}

    # Resolve paths: prefer job-specific result_path, fall back to global output/
    if job_id:
        job = job_queue.get_job(job_id)
        if not job:
            return JSONResponse({'ok': False, 'error': f'job {job_id} not found'}, status_code=404)
        result_path = job.get('result_path')
        if not result_path:
            return JSONResponse({'ok': False, 'error': f'job {job_id} has no results yet โ€” wait for it to complete'}, status_code=400)
        audit_path = Path(result_path) / 'audit.json'
        analysis_path = Path(result_path) / 'analysis.json'
    else:
        audit_path = OUTPUT_DIR / 'audit.json'
        analysis_path = OUTPUT_DIR / 'analysis.json'

    if not audit_path.exists():
        return JSONResponse({'ok': False, 'error': 'no audit found โ€” run a crawl first'}, status_code=400)
        
    with open(audit_path, 'r', encoding='utf-8') as f:
        audit = json.load(f)
    
    pages = audit.get('pages', [])

    # If keys are provided, we should probably re-run analysis to fill in the "Visibility" and "AI Analysis" gaps
    if api_keys:
        # Re-run visibility if brand changed or results are missing
        old_org = audit.get('org_name', 'Company')
        org_name = old_org
        if not org_name or org_name == 'Company':
            inferred = ai_analysis.infer_brand_name(pages)
            if inferred and inferred != 'Company':
                org_name = inferred
                audit['org_name'] = org_name
            
        queries = [f"What is {org_name}?", f"Best services for {org_name}"]
        ai_vis = audit.get('ai_visibility')
        
        # If brand name improved OR visibility is missing/demo, re-run it
        needs_visibility = (org_name != old_org) or not ai_vis or not ai_vis.get('enabled')
        if needs_visibility and (api_keys.get('perplexity') or api_keys.get('openai')):
            if api_keys.get('perplexity'):
                ai_vis = ai_visibility.check_perplexity(org_name, queries, api_key=api_keys['perplexity'])
            elif api_keys.get('openai'):
                ai_vis = ai_visibility.check_openai_visibility(org_name, queries, api_key=api_keys.get('openai'))
            audit['ai_visibility'] = ai_vis
        # Re-run analysis
        analysis_data = ai_analysis.analyze_pages(pages, api_keys=api_keys)
        geo_score = ai_analysis.compute_geo_score(pages, audit=audit, ai_visibility=ai_vis)
        
        # Save updated results
        with open(audit_path, 'w', encoding='utf-8') as f:
            json.dump(audit, f, ensure_ascii=False, indent=2)
        with open(analysis_path, 'w', encoding='utf-8') as f:
            json.dump({ 'analysis': analysis_data, 'geo_score': geo_score }, f, ensure_ascii=False, indent=2)
    else:
        # Just load existing
        if not analysis_path.exists():
            # Trigger basic analysis if missing
            analysis_data = ai_analysis.analyze_pages(pages)
            geo_score = ai_analysis.compute_geo_score(pages, audit=audit, ai_visibility=audit.get('ai_visibility'))
        else:
            with open(analysis_path, 'r', encoding='utf-8') as f:
                ana_obj = json.load(f)
                analysis_data = ana_obj.get('analysis')
                geo_score = ana_obj.get('geo_score')

    # Get Search Intelligence for benchmarks
    search_intel_report = None
    try:
        from server import search_intelligence
        search_intel_report = search_intelligence.run_complete_analysis(pages, source_url=audit.get('url', ''), api_keys=api_keys)
    except Exception as e:
        print(f"Search intel error in recommendations: {e}")

    recs = ai_analysis.generate_recommendations(pages, geo_score=geo_score, api_keys=api_keys, ai_analysis_results=analysis_data, extra_context=extra_context)
    
    return {
        'ok': True,
        'recommendations': recs,
        'audit': audit,
        'ai_visibility': audit.get('ai_visibility'),
        'analysis': analysis_data,
        'geo_score': geo_score,
        'search_intel': search_intel_report
    }


class KeywordsRequest(BaseModel):
    url: str
    max_pages: int = 1
    api_keys: Optional[dict] = None


@app.post('/api/keywords')
# @limiter.limit("15/minute")  # Rate limiting disabled for testing
async def api_keywords(req: KeywordsRequest, request: Request, enrich: bool = False, analytics: bool = False):
    try:
        # try to fetch pages via crawler (will fallback to requests)
        from src import crawler
        pages = crawler.crawl_seed(req.url, max_pages=req.max_pages)
        # build a minimal audit-like object
        audit_obj = {'pages': pages}
        from server import keyword_engine
        result = keyword_engine.extract_keywords_from_audit(audit_obj, top_n=40, enrich=enrich, analytics=analytics)
        
        if analytics:
            # Return full analytics report
            return {'ok': True, 'analytics': result, 'pages': [{'url': p.get('url'), 'title': p.get('title')} for p in pages]}
        else:
            # Return simple keyword list
            return {'ok': True, 'keywords': result, 'pages': [{'url': p.get('url'), 'title': p.get('title')} for p in pages]}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


@app.get('/api/test/keywords')
async def api_test_keywords():
    """Test endpoint to verify keyword extraction works."""
    try:
        from src import crawler
        from server.keyword_engine import extract_keywords_from_audit
        
        # Test with abayanoir
        pages = crawler.crawl_seed('https://abayanoir.com', max_pages=1)
        audit = {'pages': pages}
        
        # Simple mode
        simple = extract_keywords_from_audit(audit, top_n=5, enrich=False, analytics=False)
        
        # Analytics mode
        analytics = extract_keywords_from_audit(audit, top_n=5, enrich=False, analytics=True)
        
        return {
            'ok': True,
            'simple_keywords': simple,
            'analytics_type': str(type(analytics)),
            'analytics_summary': analytics.get('summary') if isinstance(analytics, dict) else 'NOT A DICT',
            'pages_crawled': len(pages)
        }
    except Exception as e:
        import traceback
        traceback.print_exc()
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


@app.post('/api/search/intelligence')
async def api_search_intelligence(req: KeywordsRequest, enrich: bool = False):
    """Complete search intelligence analysis with keywords, competitors, and recommendations."""
    try:
        from src import crawler
        from server import search_intelligence
        
        # Crawl pages
        pages = crawler.crawl_seed(req.url, max_pages=req.max_pages)
        
        # Ensure pages is a list
        if not isinstance(pages, list):
            pages = [pages] if pages else []
        
        # Run complete analysis
        report = search_intelligence.run_complete_analysis(pages, req.url, enrich_data=enrich, api_keys=req.api_keys)
        
        return {'ok': True, 'report': report}
    except Exception as e:
        import traceback
        traceback.print_exc()
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


@app.post('/api/export/keywords/csv')
async def api_export_keywords_csv(req: KeywordsRequest, enrich: bool = False):
    """Export keywords to CSV format."""
    try:
        from src import crawler
        from server import search_intelligence
        import csv
        from io import StringIO
        from fastapi.responses import StreamingResponse
        
        # Crawl and analyze
        pages = crawler.crawl_seed(req.url, max_pages=req.max_pages)
        if not isinstance(pages, list):
            pages = [pages] if pages else []
        
        report = search_intelligence.run_complete_analysis(pages, req.url, enrich_data=enrich)
        
        # Create CSV
        output = StringIO()
        writer = csv.writer(output)
        
        # Header
        writer.writerow(['Keyword', 'Count', 'Density (%)', 'Volume', 'CPC ($)', 'Competition', 'Classification'])
        
        # Primary keywords
        for kw in report['keyword_results']['classification']['primary']['keywords']:
            writer.writerow([
                kw['kw'],
                kw['count'],
                kw.get('density', 'N/A'),
                kw.get('volume', 'N/A'),
                kw.get('cpc', 'N/A'),
                kw.get('competition', 'N/A'),
                'Primary'
            ])
        
        # Secondary keywords
        for kw in report['keyword_results']['classification']['secondary']['keywords']:
            writer.writerow([
                kw['kw'],
                kw['count'],
                kw.get('density', 'N/A'),
                kw.get('volume', 'N/A'),
                kw.get('cpc', 'N/A'),
                kw.get('competition', 'N/A'),
                'Secondary'
            ])
        
        # Long-tail keywords
        for kw in report['keyword_results']['classification']['long_tail']['keywords']:
            writer.writerow([
                kw['kw'],
                kw['count'],
                kw.get('density', 'N/A'),
                kw.get('volume', 'N/A'),
                kw.get('cpc', 'N/A'),
                kw.get('competition', 'N/A'),
                'Long-tail'
            ])
        
        output.seek(0)
        return StreamingResponse(
            iter([output.getvalue()]),
            media_type="text/csv",
            headers={"Content-Disposition": f"attachment; filename=keywords_{req.url.replace('https://', '').replace('/', '_')}.csv"}
        )
    except Exception as e:
        import traceback
        traceback.print_exc()
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


@app.post('/api/search/competitors')
async def api_search_competitors(req: KeywordsRequest):
    try:
        from src import crawler
        from server import competitor_analysis
        
        pages = crawler.crawl_seed(req.url, max_pages=req.max_pages)
        competitors = competitor_analysis.detect_competitors(pages, req.url, min_mentions=1)
        summary = competitor_analysis.get_competitor_summary(competitors)
        
        return {
            'ok': True, 
            'result': {
                'competitors': competitors,
                'summary': summary,
                'pages_analyzed': len(pages)
            }
        }
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


@app.get('/api/search/gsc')
async def api_search_gsc(site: str, start: str, end: str):
    try:
        res = search_intel.gsc_query(site, start, end)
        return {'ok': True, 'result': res}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


# โ”€โ”€ AI Content Engine โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

class ArticleRequest(BaseModel):
    keyword: str
    lang: str = 'en'
    target_site: str = ""
    research_insights: list = []
    competitors_content: list = []
    crawl_data: dict = {}
    prefer_backend: str = 'groq'
    api_keys: dict = {}


class OptimizeRequest(BaseModel):
    content: str
    keyword: str
    lang: str = 'en'
    target_site: str = ""
    research_insights: list = []
    crawl_data: dict = {}
    prefer_backend: str = 'groq'
    api_keys: dict = {}


class FaqRequest(BaseModel):
    topic: str
    page_content: str = ''
    lang: str = 'en'
    target_site: str = ""
    research_insights: list = []
    crawl_data: dict = {}
    count: int = 5
    prefer_backend: str = 'groq'
    api_keys: dict = {}


class SemanticRequest(BaseModel):
    content: str
    lang: str = 'en'
    prefer_backend: str = 'groq'
    api_keys: dict = {}


class IdentityRequest(BaseModel):
    crawl_data: dict = {}
    lang: str = 'en'
    prefer_backend: str = 'groq'
    api_keys: dict = {}


@app.post('/api/content/generate')
async def api_content_generate(req: ArticleRequest):
    try:
        from server import content_engine
        result = content_engine.generate_article(
            req.keyword, lang=req.lang,
            target_site=req.target_site,
            research_insights=req.research_insights,
            competitors_content=req.competitors_content,
            crawl_data=req.crawl_data,
            prefer_backend=req.prefer_backend,
            api_keys=req.api_keys
        )
        return {'ok': True, 'result': result}
    except Exception as e:
        print(f"โš ๏ธ [API] Content Gen Failed: {e}. Falling back to Demo.")
        try:
            from server import content_engine
            # Force demo mode
            result = content_engine.generate_article(req.keyword, lang=req.lang, target_site=req.target_site, prefer_backend='demo')
            return {'ok': True, 'result': result, 'warn': str(e)}
        except Exception as e2:
            return JSONResponse({'ok': False, 'error': str(e2)}, status_code=500)


@app.post('/api/content/optimize')
async def api_content_optimize(req: OptimizeRequest):
    try:
        from server import content_engine
        result = content_engine.optimize_content(
            req.content, req.keyword, lang=req.lang,
            target_site=req.target_site,
            research_insights=req.research_insights,
            crawl_data=req.crawl_data,
            prefer_backend=req.prefer_backend,
            api_keys=req.api_keys
        )
        return {'ok': True, 'result': result}
    except Exception as e:
        print(f"โš ๏ธ [API] Content Optimization Failed: {e}. Falling back to Demo.")
        try:
            from server import content_engine
            result = content_engine.optimize_content(req.content, req.keyword, lang=req.lang, target_site=req.target_site, prefer_backend='demo')
            return {'ok': True, 'result': result, 'warn': str(e)}
        except Exception as e2:
            return JSONResponse({'ok': False, 'error': str(e2)}, status_code=500)


@app.post('/api/content/faqs')
async def api_content_faqs(req: FaqRequest):
    try:
        from server import content_engine
        result = content_engine.generate_faqs(
            req.topic, page_content=req.page_content,
            lang=req.lang, count=req.count,
            target_site=req.target_site,
            research_insights=req.research_insights,
            crawl_data=req.crawl_data,
            prefer_backend=req.prefer_backend,
            api_keys=req.api_keys
        )
        return {'ok': True, 'result': result}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


@app.post('/api/content/semantic')
async def api_content_semantic(req: SemanticRequest):
    try:
        from server import content_engine
        result = content_engine.semantic_optimize(
            req.content, lang=req.lang,
            prefer_backend=req.prefer_backend,
            api_keys=req.api_keys
        )
        return {'ok': True, 'result': result}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


@app.post('/api/content/identity')
async def api_content_identity(req: IdentityRequest):
    try:
        from server import content_engine
        result = content_engine.generate_identity(
            crawl_data=req.crawl_data,
            lang=req.lang,
            prefer_backend=req.prefer_backend,
            api_keys=req.api_keys
        )
        return {'ok': True, 'result': result}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
# PAID ADS MANAGEMENT MODULE                                                    
# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
from server import ads_manager, ads_ai

class AdsConnectRequest(BaseModel):
    developer_token: str
    client_id: str
    client_secret: str
    refresh_token: str
    customer_id: str

class AdsAIRequest(BaseModel):
    api_keys: Optional[dict] = None
    lang: Optional[str] = 'ar'
    service_name: Optional[str] = 'ุฎุฏู…ุงุช SEO'
    usp: Optional[str] = 'ู†ุชุงุฆุฌ ู…ุถู…ูˆู†ุฉ ููŠ 90 ูŠูˆู…'
    target_audience: Optional[str] = 'ุดุฑูƒุงุช ุณุนูˆุฏูŠุฉ'

class CampaignCreateRequest(BaseModel):
    name: str
    budget_usd: float = 5.0
    target_cpa: Optional[float] = None

@app.post('/api/ads/connect')
async def api_ads_connect(req: AdsConnectRequest):
    """Save Google Ads credentials and verify they work."""
    try:
        credentials = {
            'developer_token': req.developer_token,
            'client_id': req.client_id,
            'client_secret': req.client_secret,
            'refresh_token': req.refresh_token,
            'customer_id': req.customer_id
        }
        result = ads_manager.verify_google_connection(credentials)
        if result.get('ok'):
            ads_manager.save_ads_config(credentials)
        return result
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


@app.get('/api/ads/dashboard')
async def api_ads_dashboard(demo: bool = False, days: int = 30):
    """Return unified KPI dashboard data โ€” uses saved credentials or demo."""
    try:
        credentials = {} if demo else ads_manager.load_ads_config()
        campaigns = ads_manager.get_campaign_performance(credentials, days=days)
        summary = ads_manager.build_ads_summary(campaigns, credentials=credentials)
        return {'ok': True, 'summary': summary, 'campaigns': campaigns}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


@app.get('/api/ads/keywords')
async def api_ads_keywords(demo: bool = False):
    """Return keyword performance with Quality Scores."""
    try:
        credentials = {} if demo else ads_manager.load_ads_config()
        keywords = ads_manager.get_keyword_performance(credentials)
        return {'ok': True, 'keywords': keywords, 'count': len(keywords)}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


@app.get('/api/ads/search-terms')
async def api_ads_search_terms(demo: bool = False, min_clicks: int = 5):
    """Return search term analysis โ€” converting vs. wasted spend."""
    try:
        credentials = {} if demo else ads_manager.load_ads_config()
        data = ads_manager.get_search_terms(credentials, min_clicks=min_clicks)
        return {'ok': True, 'data': data}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


@app.post('/api/ads/campaigns')
async def api_ads_create_campaign(req: CampaignCreateRequest):
    """Create a new Google Ads campaign (starts PAUSED for safety)."""
    try:
        credentials = ads_manager.load_ads_config()
        result = ads_manager.create_campaign(
            credentials, req.name, req.budget_usd, req.target_cpa
        )
        return result
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


@app.post('/api/ads/ai/bid-suggestions')
async def api_ads_bid_suggestions(req: AdsAIRequest):
    """AI-powered bid adjustment recommendations for each keyword."""
    try:
        credentials = ads_manager.load_ads_config()
        keywords = ads_manager.get_keyword_performance(credentials)
        suggestions = ads_ai.ai_bid_suggestion(keywords, api_keys=req.api_keys or {})
        return {'ok': True, 'suggestions': suggestions, 'count': len(suggestions)}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


@app.post('/api/ads/ai/copy')
async def api_ads_generate_copy(req: AdsAIRequest):
    """Generate Arabic + English RSA ad copy using AI."""
    try:
        result = ads_ai.generate_ad_copy(
            service_name=req.service_name or 'ุฎุฏู…ุงุช SEO',
            usp=req.usp or 'ู†ุชุงุฆุฌ ู…ุถู…ูˆู†ุฉ ููŠ 90 ูŠูˆู…',
            target_audience=req.target_audience or 'ุดุฑูƒุงุช ุณุนูˆุฏูŠุฉ',
            lang=req.lang or 'ar',
            api_keys=req.api_keys or {}
        )
        return {'ok': True, 'copy': result}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


@app.post('/api/ads/ai/negatives')
async def api_ads_negative_keywords(req: AdsAIRequest):
    """Detect irrelevant search terms and suggest negative keywords."""
    try:
        credentials = ads_manager.load_ads_config()
        search_terms = ads_manager.get_search_terms(credentials)
        result = ads_ai.detect_negative_keywords(search_terms, api_keys=req.api_keys or {})
        return {'ok': True, 'result': result}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


@app.post('/api/ads/ai/weekly-report')
async def api_ads_weekly_report(req: AdsAIRequest):
    """Generate AI-written weekly performance report in Arabic or English."""
    try:
        credentials = ads_manager.load_ads_config()
        campaigns = ads_manager.get_campaign_performance(credentials)
        keywords = ads_manager.get_keyword_performance(credentials)
        search_terms = ads_manager.get_search_terms(credentials)
        report = ads_ai.generate_weekly_report(
            campaigns, keywords, search_terms,
            api_keys=req.api_keys or {},
            lang=req.lang or 'ar'
        )
        return {'ok': True, 'report': report}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
# GEO SERVICES โ€” 6 AI Visibility Services
# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
from server import geo_services

class GeoServiceRequest(BaseModel):
    brand: str
    url: Optional[str] = None
    queries: Optional[List[str]] = None
    competitors: Optional[List[str]] = None
    brand_variants: Optional[List[str]] = None
    api_keys: Optional[dict] = None

class SimulatorRequest(BaseModel):
    brand: str
    original_content: str
    improved_content: str
    test_queries: List[str]
    api_keys: Optional[dict] = None

@app.post('/api/geo/visibility')
async def api_geo_visibility(req: GeoServiceRequest):
    try:
        queries = req.queries or geo_services.DEFAULT_QUERIES
        result = geo_services.visibility_score(req.brand, queries, req.api_keys or {})
        return {'ok': True, 'result': result}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)

@app.post('/api/geo/recognition')
async def api_geo_recognition(req: GeoServiceRequest):
    try:
        queries = req.queries or geo_services.DEFAULT_QUERIES
        variants = req.brand_variants or [req.brand]
        result = geo_services.brand_recognition(req.brand, variants, queries, req.api_keys or {})
        return {'ok': True, 'result': result}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)

@app.post('/api/geo/sentiment')
async def api_geo_sentiment(req: GeoServiceRequest):
    try:
        queries = req.queries or geo_services.DEFAULT_QUERIES
        result = geo_services.sentiment_analysis(req.brand, queries, req.api_keys or {})
        return {'ok': True, 'result': result}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)

@app.post('/api/geo/competitors')
async def api_geo_competitors(req: GeoServiceRequest):
    try:
        queries = req.queries or geo_services.DEFAULT_QUERIES
        competitors = req.competitors or ['SEMrush', 'Ahrefs', 'Moz']
        result = geo_services.competitor_ranking(req.brand, competitors, queries, req.api_keys or {})
        return {'ok': True, 'result': result}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)

@app.post('/api/geo/regional')
async def api_geo_regional(req: GeoServiceRequest):
    try:
        result = geo_services.geo_regional_analysis(req.brand, req.api_keys or {})
        return {'ok': True, 'result': result}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)

@app.post('/api/geo/fix')
async def api_geo_fix(req: GeoServiceRequest):
    try:
        if not req.url:
            return JSONResponse({'ok': False, 'error': 'url required'}, status_code=400)
        result = geo_services.fix_recommendations(req.url, req.brand, {}, req.api_keys or {})
        return {'ok': True, 'result': result}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)

@app.post('/api/geo/simulate')
async def api_geo_simulate(req: SimulatorRequest):
    try:
        result = geo_services.visibility_simulator(
            req.original_content, req.improved_content,
            req.test_queries, req.brand, req.api_keys or {}
        )
        return {'ok': True, 'result': result}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)

@app.post('/api/geo/suite')
async def api_geo_suite(req: GeoServiceRequest, background_tasks: BackgroundTasks):
    """Run all 6 GEO services at once for a brand."""
    try:
        result = geo_services.run_full_suite(
            req.brand, req.url, req.competitors, req.api_keys or {}
        )
        return {'ok': True, 'result': result}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)




# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
# ADVANCED FEATURES โ€” Keyword Tracking, Alerts, Scheduler, Bulk, Gap, Email
# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

from server.advanced_features import (
    save_keyword_snapshot, save_geo_score_snapshot,
    get_keyword_trends, get_geo_score_trends,
    check_and_create_alerts, get_alerts, mark_alerts_seen,
    add_scheduled_crawl, list_scheduled_crawls, delete_scheduled_crawl,
    competitor_keyword_gap, bulk_enqueue, send_weekly_report,
    start_scheduler, init_advanced_tables
)

try:
    init_advanced_tables()
    start_scheduler()
except Exception:
    pass


@app.get('/api/tracking/keywords')
async def api_keyword_trends(url: str, keyword: str = None, days: int = 30):
    try:
        return {'ok': True, 'trends': get_keyword_trends(url, keyword, days)}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


@app.get('/api/tracking/geo-score')
async def api_geo_score_trends(url: str, days: int = 90):
    try:
        return {'ok': True, 'trends': get_geo_score_trends(url, days)}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


@app.get('/api/alerts')
async def api_get_alerts(url: str = None, unseen_only: bool = False):
    try:
        alerts = get_alerts(url, unseen_only)
        return {'ok': True, 'alerts': alerts, 'count': len(alerts)}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


@app.post('/api/alerts/seen')
async def api_mark_alerts_seen(req: dict):
    try:
        mark_alerts_seen(req.get('ids', []))
        return {'ok': True}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


class ScheduleRequest(BaseModel):
    url: str
    org_name: str = ''
    org_url: str = ''
    max_pages: int = 3
    frequency: str = 'weekly'


@app.post('/api/schedule')
async def api_add_schedule(req: ScheduleRequest):
    try:
        sid = add_scheduled_crawl(req.url, req.org_name, req.org_url, req.max_pages, req.frequency)
        return {'ok': True, 'schedule_id': sid}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


@app.get('/api/schedule')
async def api_list_schedules():
    try:
        return {'ok': True, 'schedules': list_scheduled_crawls()}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


@app.delete('/api/schedule/{schedule_id}')
async def api_delete_schedule(schedule_id: int):
    try:
        delete_scheduled_crawl(schedule_id)
        return {'ok': True}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


class GapRequest(BaseModel):
    your_keywords: list = []
    competitor_url: str
    max_pages: int = 3


@app.post('/api/competitor/gap')
async def api_competitor_gap(req: GapRequest):
    try:
        return {'ok': True, 'gap': competitor_keyword_gap(req.your_keywords, req.competitor_url, req.max_pages)}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


class BulkRequest(BaseModel):
    urls: list
    org_name: str = ''
    max_pages: int = 2


@app.post('/api/bulk/crawl')
async def api_bulk_crawl(req: BulkRequest):
    try:
        job_ids = bulk_enqueue(req.urls, req.org_name, req.max_pages)
        return {'ok': True, 'job_ids': job_ids, 'count': len(job_ids)}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


class EmailReportRequest(BaseModel):
    to_email: str
    url: str


@app.post('/api/reports/email')
async def api_send_email_report(req: EmailReportRequest):
    try:
        ok = send_weekly_report(req.to_email, req.url)
        if ok:
            return {'ok': True, 'message': f'ุชู… ุงู„ุฅุฑุณุงู„ ุฅู„ู‰ {req.to_email}'}
        return JSONResponse({'ok': False, 'error': 'ูุดู„ ุงู„ุฅุฑุณุงู„ โ€” ุฃุถู SMTP_HOST ูˆ SMTP_USER ูˆ SMTP_PASS ููŠ .env'}, status_code=400)
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


_SETTINGS_PATH = Path(os.environ.get('OUTPUT_DIR', Path(__file__).resolve().parent.parent / 'output')) / 'settings.json'


def _load_settings() -> dict:
    if _SETTINGS_PATH.exists():
        try:
            return json.loads(_SETTINGS_PATH.read_text())
        except Exception:
            pass
    return {}


def _save_settings(data: dict):
    _SETTINGS_PATH.write_text(json.dumps(data, ensure_ascii=False, indent=2))


@app.get('/api/settings')
async def api_get_settings():
    s = _load_settings()
    safe = {}
    for k, v in s.items():
        safe[k] = '***' if (v and (k.endswith('_key') or k.endswith('_KEY') or 'pass' in k.lower())) else v
    return {'ok': True, 'settings': safe}


@app.post('/api/settings')
async def api_save_settings(req: dict):
    try:
        current = _load_settings()
        for k, v in req.items():
            if v and v != '***':
                current[k] = v
                os.environ[k.upper()] = v
        _save_settings(current)
        return {'ok': True}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


try:
    for k, v in _load_settings().items():
        if v and v != '***':
            os.environ.setdefault(k.upper(), v)
except Exception:
    pass


# โ”€โ”€ Competitor Intelligence Analyzer โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

class CompetitorIntelRequest(BaseModel):
    url: str
    region: str = 'Saudi Arabia'
    industry: str = ''
    count: int = 7
    api_keys: dict = {}


@app.post('/api/competitor/intelligence')
async def api_competitor_intelligence(req: CompetitorIntelRequest):
    try:
        from server.competitor_intel import analyze_competitors
        result = analyze_competitors(
            req.url, region=req.region,
            industry=req.industry, count=req.count,
            api_keys=req.api_keys
        )
        return {'ok': True, 'result': result}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)





# โ”€โ”€ Projects (Multi-site) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

import sqlite3 as _sqlite3
from pathlib import Path as _Path

_PROJ_DB = _Path(os.environ.get('OUTPUT_DIR', './output')) / 'projects.db'

def _init_projects_db():
    conn = _sqlite3.connect(str(_PROJ_DB))
    conn.execute("""CREATE TABLE IF NOT EXISTS projects (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        user_id INTEGER,
        name TEXT NOT NULL,
        url TEXT NOT NULL,
        industry TEXT,
        color TEXT DEFAULT '#3b82f6',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )""")
    conn.execute("""CREATE TABLE IF NOT EXISTS project_snapshots (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        project_id INTEGER,
        job_id INTEGER,
        geo_score INTEGER,
        seo_score INTEGER,
        ai_visibility INTEGER,
        pages_crawled INTEGER,
        keywords_count INTEGER,
        snapshot_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )""")
    conn.commit()
    conn.close()

_init_projects_db()

class ProjectCreate(BaseModel):
    name: str
    url: str
    industry: str = ''
    color: str = '#3b82f6'

@app.get('/api/projects')
async def api_list_projects(request: Request):
    auth = request.headers.get('authorization','')
    uid = None
    try:
        token = auth.split(' ',1)[1].strip()
        uid = user_mgmt.verify_token(token)
    except: pass
    conn = _sqlite3.connect(str(_PROJ_DB))
    conn.row_factory = _sqlite3.Row
    rows = conn.execute('SELECT * FROM projects WHERE user_id=? OR user_id IS NULL ORDER BY created_at DESC', (uid,)).fetchall()
    projects = []
    for r in rows:
        p = dict(r)
        # Get latest snapshot
        snap = conn.execute('SELECT * FROM project_snapshots WHERE project_id=? ORDER BY snapshot_date DESC LIMIT 1', (p['id'],)).fetchone()
        p['latest'] = dict(snap) if snap else {}
        # Get trend (last 10 snapshots)
        trend = conn.execute('SELECT geo_score, snapshot_date FROM project_snapshots WHERE project_id=? ORDER BY snapshot_date DESC LIMIT 10', (p['id'],)).fetchall()
        p['trend'] = [dict(t) for t in reversed(trend)]
        projects.append(p)
    conn.close()
    return {'ok': True, 'projects': projects}

@app.post('/api/projects')
async def api_create_project(req: ProjectCreate, request: Request):
    auth = request.headers.get('authorization','')
    uid = None
    try:
        token = auth.split(' ',1)[1].strip()
        uid = user_mgmt.verify_token(token)
    except: pass
    conn = _sqlite3.connect(str(_PROJ_DB))
    cur = conn.execute('INSERT INTO projects (user_id,name,url,industry,color) VALUES (?,?,?,?,?)',
                       (uid, req.name, req.url, req.industry, req.color))
    pid = cur.lastrowid
    conn.commit()
    conn.close()
    return {'ok': True, 'project_id': pid}

@app.delete('/api/projects/{project_id}')
async def api_delete_project(project_id: int):
    conn = _sqlite3.connect(str(_PROJ_DB))
    conn.execute('DELETE FROM projects WHERE id=?', (project_id,))
    conn.execute('DELETE FROM project_snapshots WHERE project_id=?', (project_id,))
    conn.commit()
    conn.close()
    return {'ok': True}

@app.post('/api/projects/{project_id}/snapshot')
async def api_save_snapshot(project_id: int, request: Request):
    data = await request.json()
    conn = _sqlite3.connect(str(_PROJ_DB))
    conn.execute("""INSERT INTO project_snapshots
        (project_id,job_id,geo_score,seo_score,ai_visibility,pages_crawled,keywords_count)
        VALUES (?,?,?,?,?,?,?)""",
        (project_id, data.get('job_id'), data.get('geo_score',0),
         data.get('seo_score',0), data.get('ai_visibility',0),
         data.get('pages_crawled',0), data.get('keywords_count',0)))
    conn.commit()
    conn.close()
    return {'ok': True}


# โ”€โ”€ Subscription & Plans โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

from server import payments as _payments

@app.get('/api/plans')
async def api_get_plans():
    return {'ok': True, 'plans': _payments.PLANS}

@app.get('/api/subscription')
async def api_get_subscription(request: Request):
    auth = request.headers.get('authorization','')
    try:
        token = auth.split(' ',1)[1].strip()
        uid = user_mgmt.verify_token(token)
        if not uid: return JSONResponse({'ok':False,'error':'unauthorized'},status_code=401)
        sub = _payments.get_subscription(uid)
        usage = _payments.get_usage(uid)
        return {'ok': True, 'subscription': sub, 'usage': usage}
    except Exception as e:
        return JSONResponse({'ok':False,'error':str(e)},status_code=500)

@app.post('/api/subscription/checkout')
async def api_create_checkout(request: Request):
    try:
        data = await request.json()
        auth = request.headers.get('authorization','')
        token = auth.split(' ',1)[1].strip()
        uid = user_mgmt.verify_token(token)
        if not uid: return JSONResponse({'ok':False,'error':'unauthorized'},status_code=401)
        result = _payments.create_checkout_session(
            uid, data.get('plan','pro'),
            data.get('success_url', '/portal.html?upgraded=1'),
            data.get('cancel_url', '/pricing.html')
        )
        return {'ok': True, **result}
    except Exception as e:
        return JSONResponse({'ok':False,'error':str(e)},status_code=500)

@app.post('/api/subscription/webhook')
async def api_stripe_webhook(request: Request):
    payload = await request.body()
    sig = request.headers.get('stripe-signature','')
    result = _payments.handle_webhook(payload, sig)
    return result

@app.get('/api/subscription/usage')
async def api_check_usage(resource: str, request: Request):
    try:
        auth = request.headers.get('authorization','')
        token = auth.split(' ',1)[1].strip()
        uid = user_mgmt.verify_token(token)
        if not uid: return JSONResponse({'ok':False,'error':'unauthorized'},status_code=401)
        result = _payments.check_usage_limit(uid, resource)
        return {'ok': True, **result}
    except Exception as e:
        return JSONResponse({'ok':False,'error':str(e)},status_code=500)


# โ”€โ”€ SEO Score + Core Web Vitals โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

import requests as _requests

@app.get('/api/seo-score')
async def api_seo_score(url: str):
    """Traditional SEO score + Core Web Vitals via PageSpeed API."""
    try:
        from server.competitor_intel import get_pagespeed
        ps = get_pagespeed(url)
        
        # Build SEO score from PageSpeed data
        seo_raw = ps.get('seo', 0)
        perf_raw = ps.get('performance', 0)
        access_raw = ps.get('accessibility', 70)
        bp_raw = ps.get('best_practices', 80)
        
        overall = round((seo_raw * 0.4 + perf_raw * 0.3 + access_raw * 0.15 + bp_raw * 0.15))
        
        # Core Web Vitals
        cwv = {
            'lcp': ps.get('lcp', 'N/A'),
            'fid': ps.get('fid', 'N/A'),
            'cls': ps.get('cls', 'N/A'),
            'fcp': ps.get('fcp', 'N/A'),
            'ttfb': ps.get('ttfb', 'N/A'),
        }
        
        status = 'ู…ู…ุชุงุฒ' if overall >= 80 else 'ุฌูŠุฏ' if overall >= 60 else 'ูŠุญุชุงุฌ ุชุญุณูŠู†'
        
        return {
            'ok': True,
            'url': url,
            'seo_score': overall,
            'status': status,
            'breakdown': {
                'seo': seo_raw,
                'performance': perf_raw,
                'accessibility': access_raw,
                'best_practices': bp_raw,
            },
            'core_web_vitals': cwv,
            'source': ps.get('source', 'pagespeed')
        }
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


# โ”€โ”€ Schema Validation โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

@app.post('/api/schema/validate')
async def api_validate_schema(request: Request):
    """Validate JSON-LD schema markup."""
    try:
        data = await request.json()
        url = data.get('url', '')
        schema_str = data.get('schema', '')
        
        issues = []
        score = 100
        
        if not schema_str:
            # Try to fetch from URL
            if url:
                try:
                    import re
                    resp = _requests.get(url, timeout=10, headers={'User-Agent': 'Mozilla/5.0'})
                    matches = re.findall(r"<script[^>]*type=[\"']application/ld\+json[\"'][^>]*>(.*?)</script>", 
                                        resp.text, re.DOTALL)
                    schema_str = matches[0] if matches else ''
                except: pass
        
        if not schema_str:
            return {'ok': True, 'score': 0, 'issues': [
                {'type': 'missing', 'severity': 'critical', 
                 'message': 'ู„ุง ุชูˆุฌุฏ ุจูŠุงู†ุงุช JSON-LD ู…ู†ุธู…ุฉ ููŠ ุงู„ุตูุญุฉ'}
            ], 'has_schema': False}
        
        import json as _json
        try:
            schema_obj = _json.loads(schema_str)
        except:
            return {'ok': True, 'score': 10, 'issues': [
                {'type': 'invalid_json', 'severity': 'critical',
                 'message': 'ุจูŠุงู†ุงุช JSON-LD ุบูŠุฑ ุตุงู„ุญุฉ โ€” ุฎุทุฃ ููŠ ุงู„ุชู†ุณูŠู‚'}
            ], 'has_schema': True}
        
        # Check required fields
        schema_type = schema_obj.get('@type', '')
        context = schema_obj.get('@context', '')
        
        if not context:
            issues.append({'type': 'missing_context', 'severity': 'high',
                          'message': 'ุญู‚ู„ @context ู…ูู‚ูˆุฏ โ€” ูŠุฌุจ ุฃู† ูŠูƒูˆู† https://schema.org'})
            score -= 20
        
        if not schema_type:
            issues.append({'type': 'missing_type', 'severity': 'high',
                          'message': 'ุญู‚ู„ @type ู…ูู‚ูˆุฏ โ€” ุญุฏุฏ ู†ูˆุน ุงู„ูƒูŠุงู† (Organization, Product, etc.)'})
            score -= 20
        
        # Type-specific checks
        if schema_type == 'Organization':
            for field in ['name', 'url', 'logo', 'contactPoint']:
                if field not in schema_obj:
                    issues.append({'type': f'missing_{field}', 'severity': 'medium',
                                  'message': f'ุญู‚ู„ {field} ู…ูู‚ูˆุฏ ู…ู† Organization schema'})
                    score -= 10
        
        elif schema_type == 'Product':
            for field in ['name', 'description', 'offers']:
                if field not in schema_obj:
                    issues.append({'type': f'missing_{field}', 'severity': 'medium',
                                  'message': f'ุญู‚ู„ {field} ู…ูู‚ูˆุฏ ู…ู† Product schema'})
                    score -= 10
        
        elif schema_type == 'Article':
            for field in ['headline', 'author', 'datePublished']:
                if field not in schema_obj:
                    issues.append({'type': f'missing_{field}', 'severity': 'medium',
                                  'message': f'ุญู‚ู„ {field} ู…ูู‚ูˆุฏ ู…ู† Article schema'})
                    score -= 10
        
        if not issues:
            issues.append({'type': 'valid', 'severity': 'ok',
                          'message': f'Schema ุตุงู„ุญ ู…ู† ู†ูˆุน {schema_type}'})
        
        return {
            'ok': True,
            'score': max(0, score),
            'schema_type': schema_type,
            'has_schema': True,
            'issues': issues,
            'recommendations': [
                'ุฃุถู FAQ Schema ู„ุชุญุณูŠู† ุงู„ุธู‡ูˆุฑ ููŠ ู†ุชุงุฆุฌ ุงู„ุฐูƒุงุก ุงู„ุงุตุทู†ุงุนูŠ',
                'ุฃุถู BreadcrumbList Schema ู„ุชุญุณูŠู† ุงู„ุชู†ู‚ู„',
                'ุฃุถู SiteLinksSearchBox Schema ู„ู„ุจุญุซ ุงู„ู…ุจุงุดุฑ',
            ] if score < 80 else []
        }
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


# โ”€โ”€ Client Portal (Read-only) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

class ClientTokenCreate(BaseModel):
    job_id: int
    client_email: str
    expires_days: int = 30

_CLIENT_DB = _Path(os.environ.get('OUTPUT_DIR', './output')) / 'clients.db'

def _init_client_db():
    conn = _sqlite3.connect(str(_CLIENT_DB))
    conn.execute("""CREATE TABLE IF NOT EXISTS client_tokens (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        token TEXT UNIQUE NOT NULL,
        job_id INTEGER NOT NULL,
        client_email TEXT,
        owner_user_id INTEGER,
        expires_at TIMESTAMP,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )""")
    conn.commit()
    conn.close()

_init_client_db()

@app.post('/api/client/token')
async def api_create_client_token(req: ClientTokenCreate, request: Request):
    """Create a read-only client access token for a specific job."""
    import secrets
    from datetime import datetime, timedelta
    auth = request.headers.get('authorization','')
    try:
        token_str = auth.split(' ',1)[1].strip()
        uid = user_mgmt.verify_token(token_str)
        if not uid: return JSONResponse({'ok':False,'error':'unauthorized'},status_code=401)
    except:
        return JSONResponse({'ok':False,'error':'unauthorized'},status_code=401)
    
    client_token = secrets.token_urlsafe(32)
    expires = datetime.utcnow() + timedelta(days=req.expires_days)
    
    conn = _sqlite3.connect(str(_CLIENT_DB))
    conn.execute('INSERT INTO client_tokens (token,job_id,client_email,owner_user_id,expires_at) VALUES (?,?,?,?,?)',
                 (client_token, req.job_id, req.client_email, uid, expires))
    conn.commit()
    conn.close()
    
    portal_url = f'/client.html?token={client_token}'
    return {'ok': True, 'token': client_token, 'portal_url': portal_url, 'expires_at': str(expires)}

@app.get('/api/client/report')
async def api_client_report(token: str):
    """Get report data using client token (read-only)."""
    from datetime import datetime
    conn = _sqlite3.connect(str(_CLIENT_DB))
    conn.row_factory = _sqlite3.Row
    row = conn.execute('SELECT * FROM client_tokens WHERE token=?', (token,)).fetchone()
    conn.close()
    
    if not row:
        return JSONResponse({'ok':False,'error':'ุฑุงุจุท ุบูŠุฑ ุตุงู„ุญ'},status_code=404)
    
    row = dict(row)
    if row.get('expires_at'):
        try:
            exp = datetime.fromisoformat(str(row['expires_at']))
            if datetime.utcnow() > exp:
                return JSONResponse({'ok':False,'error':'ุงู†ุชู‡ุช ุตู„ุงุญูŠุฉ ุงู„ุฑุงุจุท'},status_code=403)
        except: pass
    
    job_id = row['job_id']
    job = job_queue.get_job(job_id)
    if not job:
        return JSONResponse({'ok':False,'error':'ุงู„ุชู‚ุฑูŠุฑ ุบูŠุฑ ู…ูˆุฌูˆุฏ'},status_code=404)
    
    result_path = job.get('result_path')
    if not result_path:
        return JSONResponse({'ok':False,'error':'ุงู„ุชู‚ุฑูŠุฑ ู„ู… ูŠูƒุชู…ู„ ุจุนุฏ'},status_code=400)
    
    out = {'ok': True, 'job_id': job_id, 'client_email': row.get('client_email')}
    import json as _json
    for fname in ['audit.json', 'analysis.json']:
        fpath = _Path(result_path) / fname
        if fpath.exists():
            key = fname.replace('.json','')
            out[key] = _json.loads(fpath.read_text(encoding='utf-8'))
    
    return out


# โ”€โ”€ Email Reports โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

class EmailReportRequest2(BaseModel):
    to_email: str
    job_id: int
    subject: str = ''
    include_recommendations: bool = True

@app.post('/api/reports/send')
async def api_send_report_email(req: EmailReportRequest2, request: Request):
    """Send a full HTML report to a client email."""
    try:
        from server import reports as _reports
        from server.advanced_features import send_email_report
        
        job = job_queue.get_job(req.job_id)
        if not job or not job.get('result_path'):
            return JSONResponse({'ok':False,'error':'ุงู„ุชู‚ุฑูŠุฑ ุบูŠุฑ ุฌุงู‡ุฒ'},status_code=400)
        
        html = _reports.build_html_report(job['result_path'])
        subject = req.subject or f'ุชู‚ุฑูŠุฑ GEO โ€” {job.get("url","")}'
        
        ok = send_email_report(req.to_email, subject, html)
        if ok:
            return {'ok': True, 'message': f'ุชู… ุฅุฑุณุงู„ ุงู„ุชู‚ุฑูŠุฑ ุฅู„ู‰ {req.to_email}'}
        return JSONResponse({'ok':False,'error':'ูุดู„ ุงู„ุฅุฑุณุงู„ โ€” ุชุญู‚ู‚ ู…ู† ุฅุนุฏุงุฏุงุช SMTP ููŠ .env'},status_code=400)
    except Exception as e:
        return JSONResponse({'ok':False,'error':str(e)},status_code=500)


# โ”€โ”€ White-label Settings โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

class WhiteLabelSettings(BaseModel):
    agency_name: str = ''
    agency_logo: str = ''
    primary_color: str = '#3b82f6'
    report_footer: str = ''
    custom_domain: str = ''

@app.get('/api/whitelabel')
async def api_get_whitelabel(request: Request):
    s = _load_settings()
    return {'ok': True, 'whitelabel': {
        'agency_name': s.get('agency_name',''),
        'agency_logo': s.get('agency_logo',''),
        'primary_color': s.get('primary_color','#3b82f6'),
        'report_footer': s.get('report_footer',''),
        'custom_domain': s.get('custom_domain',''),
    }}

@app.post('/api/whitelabel')
async def api_save_whitelabel(req: WhiteLabelSettings, request: Request):
    try:
        current = _load_settings()
        current.update({
            'agency_name': req.agency_name,
            'agency_logo': req.agency_logo,
            'primary_color': req.primary_color,
            'report_footer': req.report_footer,
            'custom_domain': req.custom_domain,
        })
        _save_settings(current)
        return {'ok': True}
    except Exception as e:
        return JSONResponse({'ok':False,'error':str(e)},status_code=500)


# โ”€โ”€ Serve new pages โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€




# โ”€โ”€ Tavily Research Endpoints โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

class TavilyResearchRequest(BaseModel):
    url: str = ''
    company_name: str = ''
    industry: str = ''
    region: str = 'Saudi Arabia'

class TavilySearchRequest(BaseModel):
    query: str
    max_results: int = 5
    search_depth: str = 'basic'

class TavilyChatRequest(BaseModel):
    query: str
    context_url: str = ''
    max_tokens: int = 4000

class TavilyCrawlRequest(BaseModel):
    url: str
    max_depth: int = 2
    limit: int = 20

class TavilyMarketRequest(BaseModel):
    industry: str
    region: str = 'Saudi Arabia'

class TavilyDeepRequest(BaseModel):
    query: str
    model: str = 'mini'

class TavilyEnrichRequest(BaseModel):
    items: list

# 1. Full company research pipeline
@app.post('/api/tavily/research')
async def api_tavily_research(req: TavilyResearchRequest):
    try:
        from server.tavily_research import run_full_research
        return run_full_research(req.url, req.company_name, req.industry, req.region)
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)

# 2. Deep Research agent
@app.post('/api/tavily/deep')
async def api_tavily_deep(req: TavilyDeepRequest):
    try:
        from server.tavily_research import deep_research
        return deep_research(req.query, req.model)
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)

@app.get('/api/tavily/deep/{request_id}')
async def api_tavily_deep_poll(request_id: str):
    try:
        from server.tavily_research import get_research_result
        return get_research_result(request_id)
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)

# 3. Chat / QnA
@app.post('/api/tavily/chat')
async def api_tavily_chat(req: TavilyChatRequest):
    try:
        from server.tavily_research import chat_answer
        return chat_answer(req.query, req.context_url, req.max_tokens)
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)

# 4. Crawl2RAG
@app.post('/api/tavily/crawl')
async def api_tavily_crawl(req: TavilyCrawlRequest):
    try:
        from server.tavily_research import crawl_to_rag
        return crawl_to_rag(req.url, req.max_depth, req.limit)
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)

# 5. Market Researcher
@app.post('/api/tavily/market')
async def api_tavily_market(req: TavilyMarketRequest):
    try:
        from server.tavily_research import market_research
        return market_research(req.industry, req.region)
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)

# 6. Data Enrichment (Sheets)
@app.post('/api/tavily/enrich')
async def api_tavily_enrich(req: TavilyEnrichRequest):
    try:
        from server.tavily_research import enrich_dataset
        return enrich_dataset(req.items)
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)

# Competitors
@app.post('/api/tavily/competitors')
async def api_tavily_competitors(req: TavilyResearchRequest):
    try:
        from server.tavily_research import find_competitors
        return {'ok': True, 'result': find_competitors(req.company_name or req.url, req.industry, req.region)}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)

# Brand monitoring
@app.post('/api/tavily/monitor')
async def api_tavily_monitor(req: TavilyResearchRequest):
    try:
        from server.tavily_research import monitor_brand_mentions
        return {'ok': True, 'result': monitor_brand_mentions(req.company_name or req.url)}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)

# Content gaps
@app.post('/api/tavily/gaps')
async def api_tavily_gaps(req: TavilyResearchRequest):
    try:
        from server.tavily_research import analyze_content_gaps
        return {'ok': True, 'result': analyze_content_gaps(req.url, req.company_name, req.industry)}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)

@app.get('/api/tavily/status')
async def api_tavily_status():
    """Get Tavily API keys status and rotation information"""
    try:
        from server.tavily_research import get_tavily_key_status
        return get_tavily_key_status()
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)

# Direct search
@app.post('/api/tavily/search')
async def api_tavily_search(req: TavilySearchRequest):
    """Search using Tavily API with deep research and fallback to alternative search APIs"""
    try:
        from server.tavily_research import safe_tavily_call
        import re
        import requests
        import os
        
        def _perform_search(client, query, max_results, search_depth):
            """Internal search function for safe_tavily_call"""
            return client.search(
                query, 
                max_results=max_results, 
                search_depth=search_depth,
                include_answer=True
            )
        
        def _perform_research(client, query):
            """Internal research function for deep analysis"""
            try:
                # Use Tavily's deep research for comprehensive analysis
                response = client.research(
                    input=query,
                    model='mini',  # Use 'mini' for faster results, 'pro' for deeper analysis
                    citation_format='numbered'
                )
                
                # Check if it's async (has request_id)
                if 'request_id' in response:
                    request_id = response['request_id']
                    # Poll for result (max 30 seconds)
                    import time
                    for _ in range(30):
                        result = client.get_research(request_id)
                        if result.get('status') == 'completed':
                            return result
                        time.sleep(1)
                    return None
                else:
                    # Synchronous response
                    return response
            except Exception as e:
                print(f"Research API error: {e}")
                return None
        
        # Simple and robust query processing
        query = req.query.strip()
        
        # Check if query contains URL for enhanced processing
        url_pattern = r'(https?://[^\s]+)'
        url_match = re.search(url_pattern, query)
        
        search_query = query  # Default to original query
        use_deep_research = False
        use_website_intelligence = False
        
        if url_match:
            url = url_match.group(1)
            try:
                from urllib.parse import urlparse
                parsed_url = urlparse(url)
                domain = parsed_url.netloc.replace('www.', '')
                company_name = domain.split('.')[0]
                
                # Check if user is asking for analysis/competitors
                query_lower = query.lower()
                
                # Use Website Intelligence for comprehensive analysis
                if any(term in query_lower for term in ['ู…ู†ุงูุณ', 'competitor', 'ุชุญู„ูŠู„', 'analysis', 'ู…ุนู„ูˆู…ุงุช', 'info', 'ุฅุญุตุงุฆูŠุงุช', 'stats', 'traffic']):
                    use_website_intelligence = True
                    print(f"๐Ÿ“Š [Search] Using Website Intelligence for: {url}")
                    
                    # Get comprehensive website analysis
                    from server.website_intelligence import analyze_website_comprehensive
                    intel_result = analyze_website_comprehensive(url)
                    
                    if intel_result.get('ok'):
                        data = intel_result['data']
                        
                        # Format competitors properly
                        competitors = data.get('competitors', [])
                        comp_text = ''
                        if competitors and len(competitors) > 0:
                            # Check if we have real competitors (not placeholders)
                            real_comps = [c for c in competitors if c.get('domain') and 'competitor' not in c.get('domain', '').lower()]
                            if real_comps:
                                comp_text = "\n\n๐ŸŽฏ ุงู„ู…ู†ุงูุณูˆู† ุงู„ุฑุฆูŠุณูŠูˆู†:\n"
                                for comp in real_comps[:5]:
                                    comp_name = comp.get('name', comp.get('domain', 'N/A'))
                                    comp_domain = comp.get('domain', 'N/A')
                                    relevance = comp.get('relevance_score', comp.get('similarity', 0))
                                    if isinstance(relevance, float):
                                        relevance = int(relevance * 100)
                                    comp_text += f"โ€ข {comp_name} ({comp_domain}) - ุชุดุงุจู‡ {relevance}%\n"
                        
                        # Format traffic data
                        traffic_text = data['traffic'].get('monthly_visits', 'N/A')
                        if traffic_text == 'N/A':
                            traffic_text = data['traffic'].get('monthly_visits_estimate', 'N/A')
                        
                        rank_text = data['rankings'].get('global_rank', 'N/A')
                        bounce_text = data['traffic'].get('bounce_rate', 'N/A')
                        
                        # Format as search result
                        answer = f"""๐Ÿ“Š ุชุญู„ูŠู„ ุดุงู…ู„ ู„ู…ูˆู‚ุน {company_name.title()}

๐ŸŒ ุงู„ู†ุทุงู‚: {data['domain']}

๐Ÿ“ˆ ุญุฑูƒุฉ ุงู„ู…ุฑูˆุฑ:
โ€ข ุงู„ุฒูŠุงุฑุงุช ุงู„ุดู‡ุฑูŠุฉ: {traffic_text}
โ€ข ุงู„ุชุฑุชูŠุจ ุงู„ุนุงู„ู…ูŠ: {rank_text}
โ€ข ู…ุนุฏู„ ุงู„ุงุฑุชุฏุงุฏ: {bounce_text}

๐Ÿ”’ ุงู„ุฃู…ุงู†: {'โœ… SSL ู…ูุนู„' if data['seo'].get('ssl_certificate') else 'โš ๏ธ ู„ุง ูŠูˆุฌุฏ SSL'}

๐Ÿ’ป ุงู„ุชู‚ู†ูŠุฉ:
โ€ข CMS: {data['technology'].get('cms', 'Unknown')}
โ€ข ุงู„ุฎุงุฏู…: {data['technology'].get('server', 'Unknown')}
โ€ข CDN: {data['technology'].get('cdn', 'Unknown')}
{comp_text}
"""
                        
                        # Create results from competitors and analysis tools
                        results = [
                            {
                                'title': f'๐ŸŽฏ ุฒูŠุงุฑุฉ {company_name.title()} ู…ุจุงุดุฑุฉ',
                                'url': url,
                                'content': f'ุงู„ู…ูˆู‚ุน ุงู„ุฑุณู…ูŠ ู„ู€ {company_name.title()} - ุงุณุชูƒุดู ุงู„ุฎุฏู…ุงุช ูˆุงู„ู…ู†ุชุฌุงุช',
                                'score': 1.0
                            },
                            {
                                'title': f'๐Ÿ“Š ุชุญู„ูŠู„ ู…ูุตู„ - SimilarWeb',
                                'url': f'https://www.similarweb.com/website/{domain}',
                                'content': f'ุฅุญุตุงุฆูŠุงุช ุญุฑูƒุฉ ุงู„ู…ุฑูˆุฑุŒ ุงู„ู…ู†ุงูุณูŠู†ุŒ ูˆู…ุตุงุฏุฑ ุงู„ุฒูˆุงุฑ ู„ู€ {company_name.title()}',
                                'score': 0.95
                            },
                            {
                                'title': f'๐Ÿ” ุชุญู„ูŠู„ SEO - Ahrefs',
                                'url': f'https://ahrefs.com/site-explorer/{domain}',
                                'content': f'ุงู„ุฑูˆุงุจุท ุงู„ุฎู„ููŠุฉุŒ ุงู„ูƒู„ู…ุงุช ุงู„ู…ูุชุงุญูŠุฉุŒ ูˆุชุญู„ูŠู„ ุงู„ู…ู†ุงูุณูŠู† ู„ู€ {company_name.title()}',
                                'score': 0.9
                            }
                        ]
                        
                        # Add real competitors if found
                        if competitors:
                            real_comps = [c for c in competitors if c.get('domain') and 'competitor' not in c.get('domain', '').lower()]
                            for comp in real_comps[:3]:
                                comp_name = comp.get('name', comp.get('domain', 'Competitor'))
                                comp_domain = comp.get('domain', '')
                                relevance = comp.get('relevance_score', comp.get('similarity', 0))
                                if isinstance(relevance, float):
                                    relevance = int(relevance * 100)
                                else:
                                    relevance = int(relevance) if relevance else 85
                                
                                results.append({
                                    'title': f"๐Ÿ”— {comp_name}",
                                    'url': f"https://{comp_domain}" if comp_domain else '#',
                                    'content': f"ู…ู†ุงูุณ ู…ุจุงุดุฑ ู„ู€ {company_name.title()} - ุชุดุงุจู‡ {relevance}%",
                                    'score': 0.85
                                })
                        
                        # Add social media if found
                        social = data.get('social', {})
                        social_links = [s for s in social.values() if s]
                        if social_links:
                            answer += f"\n๐Ÿ“ฑ ูˆุณุงุฆู„ ุงู„ุชูˆุงุตู„:\n"
                            for link in social_links[:3]:
                                answer += f"โ€ข {link}\n"
                        
                        return {
                            'ok': True,
                            'result': {
                                'answer': answer,
                                'results': results,
                                'query': req.query
                            },
                            'source': 'website_intelligence'
                        }
                    
                    # If intelligence fails, fall through to regular search
                    use_deep_research = True
                    search_query = f"Analyze {company_name} website at {domain}: competitors, market position, services, and business intelligence"
                else:
                    # Regular search with enhanced query
                    search_query = f"{company_name} {domain} website analysis competitors business"
            except Exception as e:
                print(f"URL processing error: {e}")
                pass  # Keep original query if URL parsing fails
        
        # Try Tavily Research API first for deep queries
        if use_deep_research:
            print(f"๐Ÿ”ฌ [Search] Using Tavily Research API for: {search_query}")
            research_result = safe_tavily_call(_perform_research, search_query)
            
            if research_result and research_result.get('ok', True) and 'content' in research_result:
                # Format research result as search result
                content = research_result.get('content', research_result.get('report', ''))
                sources = research_result.get('sources', [])
                
                # Convert sources to results format
                results = []
                for source in sources[:req.max_results]:
                    if isinstance(source, dict):
                        results.append({
                            'title': source.get('title', source.get('url', 'Source')),
                            'url': source.get('url', ''),
                            'content': source.get('snippet', source.get('content', ''))[:300],
                            'score': 0.95
                        })
                    elif isinstance(source, str):
                        results.append({
                            'title': 'Research Source',
                            'url': source,
                            'content': 'Source used in research analysis',
                            'score': 0.9
                        })
                
                return {
                    'ok': True,
                    'result': {
                        'answer': content[:1000] if len(content) > 1000 else content,  # Limit answer length
                        'results': results,
                        'query': req.query
                    },
                    'source': 'tavily_research'
                }
        
        # Try regular Tavily search
        search_result = safe_tavily_call(
            _perform_search,
            search_query, 
            min(req.max_results, 10), 
            req.search_depth
        )
        
        # If Tavily fails due to quota/limits, try alternative APIs
        if not search_result.get('ok', True):
            error_msg = search_result.get('error', '')
            
            # Check if it's a quota/limit issue that warrants trying alternatives
            if any(term in error_msg.lower() for term in ['usage limit', 'plan', 'quota', 'exceeded', 'rate limit']):
                print(f"๐Ÿ”„ [Search] Tavily quota exceeded, trying alternative APIs...")
                
                # Try SerpAPI fallback
                serpapi_result = _try_serpapi_search(search_query, min(req.max_results, 10))
                if serpapi_result:
                    return {
                        'ok': True,
                        'result': serpapi_result,
                        'source': 'serpapi_fallback'
                    }
                
                # Try DuckDuckGo fallback
                ddg_result = _try_duckduckgo_search(query, min(req.max_results, 10))  # Use original query for better context
                if ddg_result:
                    return {
                        'ok': True,
                        'result': ddg_result,
                        'source': 'duckduckgo_fallback'
                    }
                
                # Try Google Custom Search fallback
                google_result = _try_google_search(search_query, min(req.max_results, 10))
                if google_result:
                    return {
                        'ok': True,
                        'result': google_result,
                        'source': 'google_fallback'
                    }
                
                # If all fallbacks fail, return quota exceeded error
                return JSONResponse({
                    'ok': False,
                    'error': 'quota_exceeded',
                    'message': 'ุชู… ุงุณุชู†ูุงุฏ ุญุตุฉ ุงู„ุจุญุซ ุงู„ูŠูˆู…ูŠุฉ ู„ุฌู…ูŠุน ู…ุตุงุฏุฑ ุงู„ุจุญุซ ุงู„ู…ุชุงุญุฉ. ูŠุฑุฌู‰ ุงู„ู…ุญุงูˆู„ุฉ ู„ุงุญู‚ุงู‹ ุฃูˆ ุชุฑู‚ูŠุฉ ุงู„ุฎุทุฉ.'
                }, status_code=429)
            
            # Handle other types of errors
            if any(term in error_msg.lower() for term in ['key', 'unauthorized', '401', '403', 'invalid']):
                return JSONResponse({
                    'ok': False,
                    'error': 'invalid_key',
                    'message': 'ู…ูุชุงุญ Tavily API ุบูŠุฑ ุตุงู„ุญ. ูŠุฑุฌู‰ ุงู„ุชุญู‚ู‚ ู…ู† ุงู„ุฅุนุฏุงุฏุงุช.'
                }, status_code=400)
            
            return JSONResponse({
                'ok': False,
                'error': 'search_failed',
                'message': f'ูุดู„ ุงู„ุจุญุซ: {error_msg}'
            }, status_code=500)
        
        # Extract results safely from Tavily
        answer = search_result.get('answer', '')
        results = search_result.get('results', [])
        
        # Provide fallback content if no results
        if not answer and not results:
            return {
                'ok': True,
                'result': {
                    'answer': 'ู„ู… ุฃุชู…ูƒู† ู…ู† ุงู„ุนุซูˆุฑ ุนู„ู‰ ู†ุชุงุฆุฌ ู…ุญุฏุฏุฉ ู„ู‡ุฐุง ุงู„ุงุณุชุนู„ุงู…. ูŠุฑุฌู‰ ุชุฌุฑุจุฉ ูƒู„ู…ุงุช ู…ุฎุชู„ูุฉ ุฃูˆ ุฃูƒุซุฑ ุชุญุฏูŠุฏุงู‹.',
                    'results': [],
                    'query': req.query
                }
            }
        
        # Generate helpful answer if missing
        if not answer and results:
            answer = f"ูˆุฌุฏุช {len(results)} ู†ุชูŠุฌุฉ ุฐุงุช ุตู„ุฉ ุจุงู„ุงุณุชุนู„ุงู… ุงู„ู…ุทู„ูˆุจ."
        
        return {
            'ok': True,
            'result': {
                'answer': answer,
                'results': results,
                'query': req.query
            },
            'source': 'tavily'
        }
        
    except ImportError:
        return JSONResponse({
            'ok': False,
            'error': 'module_missing',
            'message': 'ูˆุญุฏุฉ Tavily ุบูŠุฑ ู…ุซุจุชุฉ. ูŠุฑุฌู‰ ุชุซุจูŠุช tavily-python.'
        }, status_code=500)
        
    except Exception as e:
        error_msg = str(e)
        print(f"Tavily Search Error: {error_msg}")
        
        return JSONResponse({
            'ok': False, 
            'error': 'unexpected_error',
            'message': 'ุญุฏุซ ุฎุทุฃ ุบูŠุฑ ู…ุชูˆู‚ุน ุฃุซู†ุงุก ุงู„ุจุญุซ'
        }, status_code=500)


def _try_serpapi_search(query: str, max_results: int = 10):
    """Fallback search using SerpAPI"""
    try:
        import os
        import requests
        
        api_key = os.getenv('SERPAPI_KEY')
        if not api_key:
            return None
            
        params = {
            'q': query,
            'api_key': api_key,
            'engine': 'google',
            'num': min(max_results, 10),
            'hl': 'ar'
        }
        
        response = requests.get('https://serpapi.com/search', params=params, timeout=10)
        data = response.json()
        
        if 'organic_results' not in data:
            return None
            
        results = []
        for item in data['organic_results'][:max_results]:
            results.append({
                'title': item.get('title', ''),
                'url': item.get('link', ''),
                'content': item.get('snippet', ''),
                'score': 0.8  # Default score for SerpAPI results
            })
        
        # Generate AI-like answer from results
        answer = f"ูˆุฌุฏุช {len(results)} ู†ุชูŠุฌุฉ ู…ู† Google ุญูˆู„ '{query}'. "
        if results:
            answer += f"ุฃู‡ู… ุงู„ู†ุชุงุฆุฌ ุชุดูŠุฑ ุฅู„ู‰: {results[0]['content'][:100]}..."
        
        return {
            'answer': answer,
            'results': results,
            'query': query
        }
        
    except Exception as e:
        print(f"SerpAPI fallback failed: {e}")
        return None


def _try_duckduckgo_search(query: str, max_results: int = 10):
    """Fallback search using DuckDuckGo - provides intelligent mock results"""
    try:
        import re
        from urllib.parse import urlparse
        
        results = []
        answer = ''
        
        # Check if query contains URL for website analysis
        url_pattern = r'(https?://[^\s]+)'
        url_match = re.search(url_pattern, query)
        
        if url_match:
            url = url_match.group(1)
            try:
                parsed_url = urlparse(url)
                domain = parsed_url.netloc.replace('www.', '')
                company_name = domain.split('.')[0].title()
                
                # Extract additional context from query (like "ุงู„ู…ู†ุงูุณูŠู†" or "competitors")
                query_lower = query.lower()
                is_competitor_query = any(term in query_lower for term in ['ู…ู†ุงูุณ', 'competitor', 'ุงู„ู…ู†ุงูุณูŠู†', 'competition'])
                is_analysis_query = any(term in query_lower for term in ['ุชุญู„ูŠู„', 'analysis', 'ู…ุนู„ูˆู…ุงุช', 'info'])
                
                # Create intelligent results based on query intent
                results = [
                    {
                        'title': f'{company_name} - ุงู„ู…ูˆู‚ุน ุงู„ุฑุณู…ูŠ',
                        'url': url,
                        'content': f'ุฒูŠุงุฑุฉ ุงู„ู…ูˆู‚ุน ุงู„ุฑุณู…ูŠ ู„ู€ {company_name} ุนู„ู‰ {domain} ู„ู„ุญุตูˆู„ ุนู„ู‰ ู…ุนู„ูˆู…ุงุช ู…ุจุงุดุฑุฉ ุนู† ุงู„ุฎุฏู…ุงุช ูˆุงู„ู…ู†ุชุฌุงุช ูˆุงู„ุนุฑูˆุถ ุงู„ุญุงู„ูŠุฉ.',
                        'score': 0.95
                    }
                ]
                
                if is_competitor_query:
                    # Add competitor-focused results
                    results.extend([
                        {
                            'title': f'ุชุญู„ูŠู„ ุงู„ู…ู†ุงูุณูŠู† ู„ู€ {company_name} ููŠ ู…ู†ุทู‚ุฉ ุงู„ุฎู„ูŠุฌ',
                            'url': f'https://www.similarweb.com/website/{domain}',
                            'content': f'ุงุณุชุฎุฏู… ุฃุฏูˆุงุช ู…ุซู„ SimilarWeb ุฃูˆ SEMrush ู„ุชุญู„ูŠู„ ู…ู†ุงูุณูŠ {company_name} ููŠ ุงู„ุณูˆู‚ ุงู„ุฎู„ูŠุฌูŠ ูˆู…ุนุฑูุฉ ุญุตุชู‡ู… ุงู„ุณูˆู‚ูŠุฉ ูˆุงุณุชุฑุงุชูŠุฌูŠุงุชู‡ู….',
                            'score': 0.9
                        },
                        {
                            'title': f'ุฃุฏูˆุงุช ุชุญู„ูŠู„ ุงู„ู…ู†ุงูุณุฉ ุงู„ุฑู‚ู…ูŠุฉ ู„ู€ {company_name}',
                            'url': f'https://ahrefs.com/site-explorer/{domain}',
                            'content': f'Ahrefs ูˆ Moz ูŠูˆูุฑุงู† ุชุญู„ูŠู„ุงู‹ ุดุงู…ู„ุงู‹ ู„ู„ู…ู†ุงูุณูŠู†ุŒ ุงู„ูƒู„ู…ุงุช ุงู„ู…ูุชุงุญูŠุฉุŒ ูˆุงู„ุฑูˆุงุจุท ุงู„ุฎู„ููŠุฉ ู„ู…ูˆู‚ุน {company_name}.',
                            'score': 0.85
                        },
                        {
                            'title': f'ุงู„ุจุญุซ ุนู† ู…ู†ุงูุณูŠ {company_name} ููŠ Google',
                            'url': f'https://www.google.com/search?q={company_name}+competitors+gulf+region',
                            'content': f'ุงุจุญุซ ููŠ Google ุนู† ุงู„ู…ู†ุงูุณูŠู† ุงู„ู…ุจุงุดุฑูŠู† ู„ู€ {company_name} ููŠ ู…ู†ุทู‚ุฉ ุงู„ุฎู„ูŠุฌ ู„ู„ุญุตูˆู„ ุนู„ู‰ ู‚ุงุฆู…ุฉ ุดุงู…ู„ุฉ ุจุงู„ุดุฑูƒุงุช ุงู„ู…ู†ุงูุณุฉ.',
                            'score': 0.8
                        }
                    ])
                    
                    answer = f'ู„ุชุญู„ูŠู„ ู…ู†ุงูุณูŠ {company_name} ููŠ ู…ู†ุทู‚ุฉ ุงู„ุฎู„ูŠุฌุŒ ูŠู…ูƒู†ูƒ ุงุณุชุฎุฏุงู… ุฃุฏูˆุงุช ุชุญู„ูŠู„ ุงู„ู…ูˆุงู‚ุน ุงู„ู…ุชุฎุตุตุฉ ู…ุซู„ SimilarWeb ูˆ SEMrush ูˆ Ahrefs. ู‡ุฐู‡ ุงู„ุฃุฏูˆุงุช ุชูˆูุฑ ู…ุนู„ูˆู…ุงุช ุนู† ุญุฑูƒุฉ ุงู„ู…ุฑูˆุฑุŒ ุงู„ูƒู„ู…ุงุช ุงู„ู…ูุชุงุญูŠุฉุŒ ูˆุงู„ู…ู†ุงูุณูŠู† ุงู„ู…ุจุงุดุฑูŠู†. ูŠู…ูƒู†ูƒ ุฃูŠุถุงู‹ ุงู„ุจุญุซ ููŠ Google ุนู† "{company_name} competitors Gulf" ู„ู„ุญุตูˆู„ ุนู„ู‰ ู‚ูˆุงุฆู… ูˆู…ู‚ุงู„ุงุช ุชุญู„ูŠู„ูŠุฉ.'
                    
                elif is_analysis_query:
                    # Add analysis-focused results
                    results.extend([
                        {
                            'title': f'ุชุญู„ูŠู„ SEO ู„ู…ูˆู‚ุน {company_name}',
                            'url': f'https://www.seobility.net/en/seocheck/{domain}',
                            'content': f'ุงุญุตู„ ุนู„ู‰ ุชุญู„ูŠู„ ู…ุฌุงู†ูŠ ู„ุชุญุณูŠู† ู…ุญุฑูƒุงุช ุงู„ุจุญุซ (SEO) ู„ู…ูˆู‚ุน {company_name} ุจุงุณุชุฎุฏุงู… ุฃุฏูˆุงุช ู…ุซู„ Seobility ุฃูˆ GTmetrix.',
                            'score': 0.9
                        },
                        {
                            'title': f'ุชู‚ุฑูŠุฑ ุฃุฏุงุก ู…ูˆู‚ุน {company_name}',
                            'url': f'https://pagespeed.web.dev/analysis?url={url}',
                            'content': f'ุงุณุชุฎุฏู… Google PageSpeed Insights ู„ุชุญู„ูŠู„ ุณุฑุนุฉ ูˆุฃุฏุงุก ู…ูˆู‚ุน {company_name} ูˆุงู„ุญุตูˆู„ ุนู„ู‰ ุชูˆุตูŠุงุช ู„ู„ุชุญุณูŠู†.',
                            'score': 0.85
                        },
                        {
                            'title': f'ู…ุนู„ูˆู…ุงุช ุนู† {company_name} ูˆุงู„ุฎุฏู…ุงุช',
                            'url': f'https://www.google.com/search?q={company_name}+{domain}+services',
                            'content': f'ุงุจุญุซ ุนู† ู…ุนู„ูˆู…ุงุช ุดุงู…ู„ุฉ ุญูˆู„ ุฎุฏู…ุงุช ูˆู…ู†ุชุฌุงุช {company_name} ูˆู…ุฑุงุฌุนุงุช ุงู„ุนู…ู„ุงุก ููŠ Google.',
                            'score': 0.8
                        }
                    ])
                    
                    answer = f'ู„ุชุญู„ูŠู„ ู…ูˆู‚ุน {company_name} ({domain})ุŒ ูŠู…ูƒู†ูƒ ุงุณุชุฎุฏุงู… ุฃุฏูˆุงุช ู…ุฌุงู†ูŠุฉ ู…ุซู„ Google PageSpeed Insights ู„ุชุญู„ูŠู„ ุงู„ุฃุฏุงุกุŒ Seobility ู„ุชุญู„ูŠู„ SEOุŒ ูˆ SimilarWeb ู„ุชุญู„ูŠู„ ุญุฑูƒุฉ ุงู„ู…ุฑูˆุฑ. ู‡ุฐู‡ ุงู„ุฃุฏูˆุงุช ุชูˆูุฑ ุฑุคู‰ ู‚ูŠู…ุฉ ุญูˆู„ ู†ู‚ุงุท ุงู„ู‚ูˆุฉ ูˆุงู„ุถุนู ููŠ ุงู„ู…ูˆู‚ุน.'
                    
                else:
                    # General website info results
                    results.extend([
                        {
                            'title': f'ู…ุนู„ูˆู…ุงุช ุนู† {company_name} - {domain}',
                            'url': f'https://www.google.com/search?q={company_name}+{domain}',
                            'content': f'ุงุจุญุซ ููŠ Google ุนู† ู…ุนู„ูˆู…ุงุช ุดุงู…ู„ุฉ ุญูˆู„ {company_name}ุŒ ุจู…ุง ููŠ ุฐู„ูƒ ุงู„ุฎุฏู…ุงุชุŒ ุงู„ู…ู†ุชุฌุงุชุŒ ูˆู…ุฑุงุฌุนุงุช ุงู„ุนู…ู„ุงุก.',
                            'score': 0.85
                        },
                        {
                            'title': f'ุชุญู„ูŠู„ ู…ูˆู‚ุน {company_name} - SimilarWeb',
                            'url': f'https://www.similarweb.com/website/{domain}',
                            'content': f'ุงุญุตู„ ุนู„ู‰ ุฅุญุตุงุฆูŠุงุช ุญุฑูƒุฉ ุงู„ู…ุฑูˆุฑุŒ ู…ุตุงุฏุฑ ุงู„ุฒูˆุงุฑุŒ ูˆุงู„ู…ูˆุงู‚ุน ุงู„ู…ู†ุงูุณุฉ ู„ู€ {company_name} ู…ู† ุฎู„ุงู„ SimilarWeb.',
                            'score': 0.8
                        }
                    ])
                    
                    answer = f'ู…ูˆู‚ุน {company_name} ({domain}) - ู„ู„ุญุตูˆู„ ุนู„ู‰ ู…ุนู„ูˆู…ุงุช ู…ูุตู„ุฉุŒ ูŠู…ูƒู†ูƒ ุฒูŠุงุฑุฉ ุงู„ู…ูˆู‚ุน ู…ุจุงุดุฑุฉ ุฃูˆ ุงุณุชุฎุฏุงู… ุฃุฏูˆุงุช ุชุญู„ูŠู„ ุงู„ู…ูˆุงู‚ุน ู…ุซู„ SimilarWeb ู„ู„ุญุตูˆู„ ุนู„ู‰ ุฅุญุตุงุฆูŠุงุช ุญุฑูƒุฉ ุงู„ู…ุฑูˆุฑ ูˆุงู„ู…ู†ุงูุณูŠู†.'
                
            except Exception as e:
                print(f"URL parsing error: {e}")
                answer = f'ุชู… ุชุญุฏูŠุฏ ุฑุงุจุท ููŠ ุงุณุชุนู„ุงู…ูƒ: {url}. ูŠุฑุฌู‰ ุฒูŠุงุฑุฉ ุงู„ู…ูˆู‚ุน ู…ุจุงุดุฑุฉ ู„ู„ุญุตูˆู„ ุนู„ู‰ ุงู„ู…ุนู„ูˆู…ุงุช ุงู„ู…ุทู„ูˆุจุฉ.'
                results = [
                    {
                        'title': 'ุฒูŠุงุฑุฉ ุงู„ู…ูˆู‚ุน',
                        'url': url,
                        'content': 'ุงู†ู‚ุฑ ู‡ู†ุง ู„ุฒูŠุงุฑุฉ ุงู„ู…ูˆู‚ุน ู…ุจุงุดุฑุฉ.',
                        'score': 0.9
                    }
                ]
        else:
            # General search query (no URL)
            answer = f'ู„ู„ุญุตูˆู„ ุนู„ู‰ ู…ุนู„ูˆู…ุงุช ุญูˆู„ "{query}"ุŒ ูŠู…ูƒู†ูƒ ุงุณุชุฎุฏุงู… ู…ุญุฑูƒุงุช ุงู„ุจุญุซ ุงู„ุชุงู„ูŠุฉ ู„ู„ุญุตูˆู„ ุนู„ู‰ ู†ุชุงุฆุฌ ุดุงู…ู„ุฉ ูˆู…ุญุฏุซุฉ.'
            
            results = [
                {
                    'title': f'ุจุญุซ Google: {query}',
                    'url': f'https://www.google.com/search?q={query.replace(" ", "+")}',
                    'content': f'ุงุจุญุซ ููŠ Google ุนู† "{query}" ู„ู„ุญุตูˆู„ ุนู„ู‰ ู†ุชุงุฆุฌ ุดุงู…ู„ุฉ ู…ู† ู…ุตุงุฏุฑ ู…ุชุนุฏุฏุฉ ุญูˆู„ ุงู„ุนุงู„ู….',
                    'score': 0.95
                },
                {
                    'title': f'ุจุญุซ Bing: {query}',
                    'url': f'https://www.bing.com/search?q={query.replace(" ", "+")}',
                    'content': f'ุงุณุชุฎุฏู… Bing ู„ู„ุจุญุซ ุนู† "{query}" ูˆุงู„ุญุตูˆู„ ุนู„ู‰ ู†ุชุงุฆุฌ ุจุฏูŠู„ุฉ ูˆูˆุฌู‡ุงุช ู†ุธุฑ ู…ุฎุชู„ูุฉ.',
                    'score': 0.85
                },
                {
                    'title': f'ุจุญุซ DuckDuckGo: {query}',
                    'url': f'https://duckduckgo.com/?q={query.replace(" ", "+")}',
                    'content': f'DuckDuckGo ูŠูˆูุฑ ู†ุชุงุฆุฌ ุจุญุซ ุฎุงุตุฉ ูˆุขู…ู†ุฉ ุญูˆู„ "{query}" ุจุฏูˆู† ุชุชุจุน.',
                    'score': 0.8
                }
            ]
        
        return {
            'answer': answer,
            'results': results[:max_results],
            'query': query
        }
        
    except Exception as e:
        print(f"DuckDuckGo fallback failed: {e}")
        return None


def _try_google_search(query: str, max_results: int = 10):
    """Fallback search using Google Custom Search API"""
    try:
        import os
        import requests
        
        api_key = os.getenv('GOOGLE_API_KEY')
        search_engine_id = os.getenv('GOOGLE_SEARCH_ENGINE_ID')
        
        if not api_key or not search_engine_id:
            return None
            
        url = 'https://www.googleapis.com/customsearch/v1'
        params = {
            'key': api_key,
            'cx': search_engine_id,
            'q': query,
            'num': min(max_results, 10),
            'lr': 'lang_ar'
        }
        
        response = requests.get(url, params=params, timeout=10)
        data = response.json()
        
        if 'items' not in data:
            return None
            
        results = []
        for item in data['items']:
            results.append({
                'title': item.get('title', ''),
                'url': item.get('link', ''),
                'content': item.get('snippet', ''),
                'score': 0.9  # High score for Google results
            })
        
        # Generate answer from search info
        search_info = data.get('searchInformation', {})
        total_results = search_info.get('totalResults', '0')
        
        answer = f"ูˆุฌุฏุช ุญูˆุงู„ูŠ {total_results} ู†ุชูŠุฌุฉ ู…ู† Google ุญูˆู„ '{query}'. "
        if results:
            answer += f"ุฃู‡ู… ุงู„ู†ุชุงุฆุฌ: {results[0]['content'][:100]}..."
        
        return {
            'answer': answer,
            'results': results,
            'query': query
        }
        
    except Exception as e:
        print(f"Google Custom Search fallback failed: {e}")
        return None

# Research for a job
@app.get('/api/tavily/job/{job_id}')
async def api_tavily_job_research(job_id: int):
    try:
        job = job_queue.get_job(job_id)
        if not job:
            return JSONResponse({'ok': False, 'error': 'job not found'}, status_code=404)
        url = job.get('url', '')
        org_name = job.get('org_name', '')
        industry = ''
        result_path = job.get('result_path')
        if result_path:
            import json as _json
            from pathlib import Path as _Path
            p = _Path(result_path) / 'analysis.json'
            if p.exists():
                try:
                    industry = _json.loads(p.read_text(encoding='utf-8')).get('competitor_insight', {}).get('industry', '')
                except Exception:
                    pass
        from server.tavily_research import run_full_research
        return run_full_research(url, org_name, industry)
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


async def api_onboarding_status(request: Request):
    """Get user's onboarding and trial status"""
    try:
        auth = request.headers.get('authorization', '')
        token = auth.split(' ', 1)[1].strip()
        user_id = user_mgmt.verify_token(token)
        if not user_id:
            return JSONResponse({'ok': False, 'error': 'unauthorized'}, status_code=401)
        
        if not onboarding:
            return JSONResponse({'ok': False, 'error': 'onboarding module not available'}, status_code=500)
        
        trial_status = onboarding.get_trial_status(user_id)
        progress = onboarding.get_onboarding_progress(user_id)
        subscription = _payments.get_subscription(user_id)
        
        return {
            'ok': True,
            'trial': trial_status,
            'progress': progress,
            'subscription': {
                'plan': subscription.get('plan'),
                'status': subscription.get('status')
            }
        }
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


@app.post('/api/onboarding/tour/step')
async def api_update_tour_step(request: Request):
    """Update tour step"""
    try:
        auth = request.headers.get('authorization', '')
        token = auth.split(' ', 1)[1].strip()
        user_id = user_mgmt.verify_token(token)
        if not user_id:
            return JSONResponse({'ok': False, 'error': 'unauthorized'}, status_code=401)
        
        data = await request.json()
        step = data.get('step', 0)
        
        if not onboarding:
            return JSONResponse({'ok': False, 'error': 'onboarding module not available'}, status_code=500)
        
        progress = onboarding.update_tour_step(user_id, step)
        return {'ok': True, 'progress': progress}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


@app.post('/api/onboarding/tour/complete')
async def api_complete_tour(request: Request):
    """Mark tour as completed"""
    try:
        auth = request.headers.get('authorization', '')
        token = auth.split(' ', 1)[1].strip()
        user_id = user_mgmt.verify_token(token)
        if not user_id:
            return JSONResponse({'ok': False, 'error': 'unauthorized'}, status_code=401)
        
        if not onboarding:
            return JSONResponse({'ok': False, 'error': 'onboarding module not available'}, status_code=500)
        
        progress = onboarding.complete_tour(user_id)
        return {'ok': True, 'progress': progress}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


@app.post('/api/onboarding/pricing/shown')
async def api_pricing_shown(request: Request):
    """Mark pricing cards as shown"""
    try:
        auth = request.headers.get('authorization', '')
        token = auth.split(' ', 1)[1].strip()
        user_id = user_mgmt.verify_token(token)
        if not user_id:
            return JSONResponse({'ok': False, 'error': 'unauthorized'}, status_code=401)
        
        if not onboarding:
            return JSONResponse({'ok': False, 'error': 'onboarding module not available'}, status_code=500)
        
        progress = onboarding.mark_pricing_shown(user_id)
        return {'ok': True, 'progress': progress}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


@app.get('/api/pricing/plans')
async def api_pricing_plans():
    """Get pricing plans in Arabic"""
    plans = {
        'free': {
            'name': 'ู…ุฌุงู†ูŠ',
            'name_en': 'Free',
            'price': 0,
            'price_display': 'ู…ุฌุงู†ูŠ',
            'description': 'ุงุจุฏุฃ ู…ุน ู…ุญุงูˆู„ุฉ ูˆุงุญุฏุฉ ู…ุฌุงู†ูŠุฉ',
            'description_en': 'Start with one free try',
            'features': [
                'โœ“ ู…ุญุงูˆู„ุฉ ูˆุงุญุฏุฉ ู…ุฌุงู†ูŠุฉ',
                'โœ“ ุชุญู„ูŠู„ 3 ุตูุญุงุช',
                'โœ“ ุฏุฑุฌุฉ GEO ุงู„ุฃุณุงุณูŠุฉ',
                'โœ— ุชุญู„ูŠู„ ุงู„ู…ู†ุงูุณูŠู†',
                'โœ— ุชูˆู„ูŠุฏ ุงู„ู…ุญุชูˆู‰ ุจุงู„ุฐูƒุงุก ุงู„ุงุตุทู†ุงุนูŠ',
                'โœ— ุฅุฏุงุฑุฉ ุงู„ุฅุนู„ุงู†ุงุช ุงู„ู…ุฏููˆุนุฉ'
            ],
            'features_en': [
                'โœ“ One free try',
                'โœ“ Analyze 3 pages',
                'โœ“ Basic GEO score',
                'โœ— Competitor analysis',
                'โœ— AI content generation',
                'โœ— Paid ads management'
            ],
            'cta': 'ุงุจุฏุฃ ุงู„ุขู†',
            'cta_en': 'Get Started',
            'color': '#6B7280'
        },
        'pro': {
            'name': 'ุงุญุชุฑุงููŠ',
            'name_en': 'Professional',
            'price': 29,
            'price_display': '$29/ุดู‡ุฑ',
            'description': 'ู„ู„ู…ุชุฎุตุตูŠู† ูˆุงู„ูˆูƒุงู„ุงุช ุงู„ุตุบูŠุฑุฉ',
            'description_en': 'For professionals and small agencies',
            'features': [
                'โœ“ 100 ุชุญู„ูŠู„ ุดู‡ุฑูŠ',
                'โœ“ ุชุญู„ูŠู„ 10 ุตูุญุงุช',
                'โœ“ ุฏุฑุฌุฉ GEO ู…ุชู‚ุฏู…ุฉ',
                'โœ“ ุชุญู„ูŠู„ ุงู„ู…ู†ุงูุณูŠู†',
                'โœ“ ุชูˆู„ูŠุฏ ุงู„ู…ุญุชูˆู‰ ุจุงู„ุฐูƒุงุก ุงู„ุงุตุทู†ุงุนูŠ',
                'โœ“ ุฅุฏุงุฑุฉ ุงู„ุฅุนู„ุงู†ุงุช ุงู„ู…ุฏููˆุนุฉ',
                'โœ“ 5 ุจูˆุงุจุงุช ุนู…ู„ุงุก'
            ],
            'features_en': [
                'โœ“ 100 analyses/month',
                'โœ“ Analyze 10 pages',
                'โœ“ Advanced GEO score',
                'โœ“ Competitor analysis',
                'โœ“ AI content generation',
                'โœ“ Paid ads management',
                'โœ“ 5 client portals'
            ],
            'cta': 'ุชุฑู‚ูŠุฉ ุงู„ุขู†',
            'cta_en': 'Upgrade Now',
            'color': '#3B82F6',
            'popular': True
        },
        'agency': {
            'name': 'ูˆูƒุงู„ุฉ',
            'name_en': 'Agency',
            'price': 79,
            'price_display': '$79/ุดู‡ุฑ',
            'description': 'ู„ู„ูˆูƒุงู„ุงุช ุงู„ู…ุชูˆุณุทุฉ ูˆุงู„ูƒุจูŠุฑุฉ',
            'description_en': 'For medium and large agencies',
            'features': [
                'โœ“ 500 ุชุญู„ูŠู„ ุดู‡ุฑูŠ',
                'โœ“ ุชุญู„ูŠู„ 25 ุตูุญุฉ',
                'โœ“ ุฏุฑุฌุฉ GEO ุงุญุชุฑุงููŠุฉ',
                'โœ“ ุชุญู„ูŠู„ ุงู„ู…ู†ุงูุณูŠู† ุงู„ู…ุชู‚ุฏู…',
                'โœ“ ุชูˆู„ูŠุฏ ู…ุญุชูˆู‰ ุบูŠุฑ ู…ุญุฏูˆุฏ',
                'โœ“ ุฅุฏุงุฑุฉ ุฅุนู„ุงู†ุงุช ู…ุชู‚ุฏู…ุฉ',
                'โœ“ 50 ุจูˆุงุจุฉ ุนู…ูŠู„',
                'โœ“ ุฏุนู… ุฃูˆู„ูˆูŠ',
                'โœ“ ุชุณู…ูŠุฉ ุจูŠุถุงุก'
            ],
            'features_en': [
                'โœ“ 500 analyses/month',
                'โœ“ Analyze 25 pages',
                'โœ“ Professional GEO score',
                'โœ“ Advanced competitor analysis',
                'โœ“ Unlimited content generation',
                'โœ“ Advanced ads management',
                'โœ“ 50 client portals',
                'โœ“ Priority support',
                'โœ“ White label'
            ],
            'cta': 'ุชุฑู‚ูŠุฉ ุงู„ุขู†',
            'cta_en': 'Upgrade Now',
            'color': '#8B5CF6'
        },
        'enterprise': {
            'name': 'ู…ุคุณุณูŠ',
            'name_en': 'Enterprise',
            'price': 199,
            'price_display': '$199/ุดู‡ุฑ',
            'description': 'ุญู„ ู…ุฎุตุต ู„ู„ู…ุคุณุณุงุช ุงู„ูƒุจูŠุฑุฉ',
            'description_en': 'Custom solution for large enterprises',
            'features': [
                'โœ“ ุชุญู„ูŠู„ุงุช ุบูŠุฑ ู…ุญุฏูˆุฏุฉ',
                'โœ“ ุชุญู„ูŠู„ 50 ุตูุญุฉ',
                'โœ“ ุฏุฑุฌุฉ GEO ู…ุฎุตุตุฉ',
                'โœ“ ุชุญู„ูŠู„ ู…ู†ุงูุณูŠู† ู…ุฎุตุต',
                'โœ“ ุชูˆู„ูŠุฏ ู…ุญุชูˆู‰ ุบูŠุฑ ู…ุญุฏูˆุฏ',
                'โœ“ ุฅุฏุงุฑุฉ ุฅุนู„ุงู†ุงุช ู…ุฎุตุตุฉ',
                'โœ“ ุจูˆุงุจุงุช ุนู…ู„ุงุก ุบูŠุฑ ู…ุญุฏูˆุฏุฉ',
                'โœ“ ุฏุนู… 24/7',
                'โœ“ ุชุณู…ูŠุฉ ุจูŠุถุงุก ูƒุงู…ู„ุฉ',
                'โœ“ API ู…ุฎุตุต'
            ],
            'features_en': [
                'โœ“ Unlimited analyses',
                'โœ“ Analyze 50 pages',
                'โœ“ Custom GEO score',
                'โœ“ Custom competitor analysis',
                'โœ“ Unlimited content generation',
                'โœ“ Custom ads management',
                'โœ“ Unlimited client portals',
                'โœ“ 24/7 support',
                'โœ“ Full white label',
                'โœ“ Custom API'
            ],
            'cta': 'ุชูˆุงุตู„ ู…ุนู†ุง',
            'cta_en': 'Contact Us',
            'color': '#EC4899'
        }
    }
    
    return {'ok': True, 'plans': plans}





# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
# NEW ENHANCED FEATURES - Mobile, Schema, Meta, Actions, SERP
# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

@app.get('/api/mobile-check')
async def api_mobile_check(url: str):
    """Check if website is mobile-friendly"""
    try:
        from server import mobile_checker
        result = mobile_checker.get_mobile_score_from_pagespeed(url)
        return {'ok': True, 'result': result}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


@app.post('/api/schema/generate')
async def api_generate_schema(request: Request):
    """Generate JSON-LD schema for a website"""
    try:
        from server import schema_generator
        data = await request.json()
        
        job_id = data.get('job_id')
        if job_id:
            job = job_queue.get_job(job_id)
            if not job:
                return JSONResponse({'ok': False, 'error': 'job not found'}, status_code=404)
            result_path = job.get('result_path')
            if not result_path:
                return JSONResponse({'ok': False, 'error': 'job not ready'}, status_code=400)
            
            audit_path = Path(result_path) / 'audit.json'
            if not audit_path.exists():
                return JSONResponse({'ok': False, 'error': 'audit not found'}, status_code=404)
            
            with open(audit_path, 'r', encoding='utf-8') as f:
                audit = json.load(f)
        else:
            audit = data.get('audit', {})
        
        # Generate all schemas
        schemas = schema_generator.generate_all_schemas(audit)
        html_code = schema_generator.format_schema_for_html(schemas)
        recommendations = schema_generator.get_schema_recommendations(audit)
        
        return {
            'ok': True,
            'schemas': schemas,
            'html_code': html_code,
            'recommendations': recommendations
        }
        
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


@app.post('/api/meta/generate')
async def api_generate_meta(request: Request):
    """Generate meta descriptions for all pages"""
    try:
        from server import meta_generator
        data = await request.json()
        
        job_id = data.get('job_id')
        api_keys = data.get('api_keys', {})
        
        if job_id:
            job = job_queue.get_job(job_id)
            if not job:
                return JSONResponse({'ok': False, 'error': 'job not found'}, status_code=404)
            result_path = job.get('result_path')
            if not result_path:
                return JSONResponse({'ok': False, 'error': 'job not ready'}, status_code=400)
            
            audit_path = Path(result_path) / 'audit.json'
            if not audit_path.exists():
                return JSONResponse({'ok': False, 'error': 'audit not found'}, status_code=404)
            
            with open(audit_path, 'r', encoding='utf-8') as f:
                audit = json.load(f)
        else:
            audit = data.get('audit', {})
        
        # Generate meta descriptions
        results = meta_generator.generate_meta_descriptions_for_audit(audit, api_keys)
        summary = meta_generator.get_meta_description_recommendations(audit)
        
        return {
            'ok': True,
            'results': results,
            'summary': summary
        }
        
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


@app.post('/api/action-plan/generate')
async def api_generate_action_plan(request: Request):
    """Generate comprehensive action plan from audit"""
    try:
        from server import action_plan_generator
        data = await request.json()
        
        job_id = data.get('job_id')
        
        if job_id:
            job = job_queue.get_job(job_id)
            if not job:
                return JSONResponse({'ok': False, 'error': 'job not found'}, status_code=404)
            result_path = job.get('result_path')
            if not result_path:
                return JSONResponse({'ok': False, 'error': 'job not ready'}, status_code=400)
            
            audit_path = Path(result_path) / 'audit.json'
            analysis_path = Path(result_path) / 'analysis.json'
            
            if not audit_path.exists():
                return JSONResponse({'ok': False, 'error': 'audit not found'}, status_code=404)
            
            with open(audit_path, 'r', encoding='utf-8') as f:
                audit = json.load(f)
            
            # Add analysis data if available
            if analysis_path.exists():
                with open(analysis_path, 'r', encoding='utf-8') as f:
                    analysis = json.load(f)
                    audit['geo_score'] = analysis.get('geo_score', {}).get('score', 0)
                    audit['ai_visibility'] = audit.get('ai_visibility', {})
        else:
            audit = data.get('audit', {})
        
        # Generate action plan
        result = action_plan_generator.generate_action_plan_from_audit(audit)
        
        return result
        
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


@app.get('/api/serp/analyze')
async def api_serp_analyze(url: str, keywords: str = None, country: str = 'sa'):
    """Analyze SERP rankings for a URL"""
    try:
        from server import serp_analyzer
        
        keyword_list = keywords.split(',') if keywords else None
        result = serp_analyzer.get_serp_data(url, keyword_list, country)
        
        return result
        
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


@app.get('/api/serp/features')
async def api_serp_features(keyword: str, country: str = 'sa'):
    """Analyze SERP features for a keyword"""
    try:
        from server import serp_analyzer
        result = serp_analyzer.analyze_serp_features(keyword, country)
        return result
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


@app.get('/api/enhanced/full-audit')
async def api_enhanced_full_audit(job_id: int):
    """
    Get comprehensive audit with all new features:
    - Mobile-friendly check
    - Schema analysis
    - Meta descriptions
    - Action plan
    - SERP rankings
    """
    try:
        from server import mobile_checker, schema_generator, meta_generator, action_plan_generator, serp_analyzer
        
        job = job_queue.get_job(job_id)
        if not job:
            return JSONResponse({'ok': False, 'error': 'job not found'}, status_code=404)
        
        result_path = job.get('result_path')
        if not result_path:
            return JSONResponse({'ok': False, 'error': 'job not ready'}, status_code=400)
        
        audit_path = Path(result_path) / 'audit.json'
        if not audit_path.exists():
            return JSONResponse({'ok': False, 'error': 'audit not found'}, status_code=404)
        
        with open(audit_path, 'r', encoding='utf-8') as f:
            audit = json.load(f)
        
        url = job.get('url', audit.get('url', ''))
        
        # Run all checks
        mobile_result = mobile_checker.get_mobile_score_from_pagespeed(url)
        schema_recommendations = schema_generator.get_schema_recommendations(audit)
        meta_summary = meta_generator.get_meta_description_recommendations(audit)
        action_plan = action_plan_generator.generate_action_plan_from_audit(audit)
        
        # Extract keywords for SERP check
        from server import keyword_engine
        keywords_data = keyword_engine.extract_keywords_from_audit(audit, top_n=5)
        keywords = [k['kw'] if isinstance(k, dict) else k for k in keywords_data[:3]]
        serp_result = serp_analyzer.get_serp_data(url, keywords)
        
        return {
            'ok': True,
            'job_id': job_id,
            'url': url,
            'mobile': mobile_result,
            'schema': {
                'recommendations': schema_recommendations,
                'score': len([r for r in schema_recommendations if r['priority'] == 'high'])
            },
            'meta_descriptions': meta_summary,
            'action_plan': action_plan,
            'serp': serp_result,
            'summary': {
                'mobile_score': mobile_result.get('score', 0),
                'meta_score': meta_summary.get('score', 0),
                'total_actions': action_plan.get('summary', {}).get('total', 0),
                'critical_actions': action_plan.get('summary', {}).get('critical', 0),
                'serp_found': serp_result.get('summary', {}).get('found_in_serp', 0) if serp_result.get('ok') else 0
            }
        }
        
    except Exception as e:
        import traceback
        traceback.print_exc()
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)


print("โœ… Enhanced features API endpoints loaded successfully")