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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from fastapi import FastAPI, HTTPException, Depends, Request
from fastapi.middleware.cors import CORSMiddleware
from pymongo import MongoClient
from pymongo.errors import ConnectionFailure
import os
import time
from typing import List, Optional
from datetime import datetime, timedelta, timezone
from app.models import BudgetRecommendation, Expense, Budget, CategoryExpense, RecommendationRequest, RecommendationResponse, RecommendationByNameRequest, RecommendationByNameRequest
from app.smart_recommendation import SmartBudgetRecommender

app = FastAPI(title="Smart Budget Recommendation API", version="1.0.0")

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

# MongoDB connection - Get from environment variable (set as secret in Hugging Face)
MONGODB_URI = os.getenv("MONGODB_URI")
if not MONGODB_URI:
    raise ValueError("MONGODB_URI environment variable is required. Please set it in Hugging Face secrets.")

try:
    client = MongoClient(MONGODB_URI)
    db = client.expense
    # Test connection
    client.admin.command('ping')
    print("Successfully connected to MongoDB")
except ConnectionFailure as e:
    print(f"Failed to connect to MongoDB: {e}")
    raise

# Initialize Smart Budget Recommender
recommender = SmartBudgetRecommender(db)

# IST timezone (UTC+5:30)
IST = timezone(timedelta(hours=5, minutes=30))

def log_api_call(db, name: str, status: str, response_time: float, endpoint: str = None, error: str = None):
    """
    Log API call to MongoDB api_logs collection
    
    Args:
        db: MongoDB database instance
        name: API name (e.g., "smart budget recommendation")
        status: "success" or "fail"
        response_time: Response time in seconds
        endpoint: Optional endpoint path
        error: Optional error message
    """
    try:
        # Get current time in IST
        ist_time = datetime.now(IST)
        # Format: DD-MM-YYYY HH:MM:SS:IST
        timestamp_str = ist_time.strftime("%d-%m-%Y %H:%M:%S:IST")
        
        # Extract user_id from endpoint (e.g., "/recommendations/user123" -> "user123")
        user_id = None
        if endpoint:
            # Extract user_id from path patterns like "/recommendations/{user_id}" or "/category-expenses/{user_id}"
            parts = endpoint.strip("/").split("/")
            if len(parts) >= 2:
                user_id = parts[1]  # Get the user_id part
        
        log_entry = {
            "name": name,
            "status": status,
            "date": timestamp_str,  # Combined date and time in IST
            "response_time": round(response_time, 3),  # Round to 3 decimal places
            "user_id": user_id,
        }
        
        if error:
            log_entry["error"] = error
        
        # Insert into api_logs collection
        db.api_logs.insert_one(log_entry)
    except Exception as e:
        # Don't fail the API call if logging fails
        print(f"Failed to log API call: {e}")

@app.middleware("http")
async def log_requests(request: Request, call_next):
    """Middleware to log API requests and track response time"""
    start_time = time.time()
    
    # Only log specific endpoints
    endpoint = request.url.path
    should_log = endpoint in ["/recommendations", "/category-expenses"] or endpoint.startswith("/recommendations/") or endpoint.startswith("/category-expenses/")
    
    if should_log:
        try:
            response = await call_next(request)
            process_time = time.time() - start_time
            
            # Determine status
            status = "success" if response.status_code < 400 else "fail"
            
            # Log the API call
            log_api_call(
                db=db,
                name="smart budget recommendation",
                status=status,
                response_time=process_time,
                endpoint=endpoint
            )
            
            return response
        except Exception as e:
            process_time = time.time() - start_time
            # Log failure
            log_api_call(
                db=db,
                name="smart budget recommendation",
                status="fail",
                response_time=process_time,
                endpoint=endpoint,
                error=str(e)
            )
            raise
    else:
        # For other endpoints, just pass through
        return await call_next(request)

@app.get("/")
async def root():
    return {"message": "Smart Budget Recommendation API", "status": "running"}

@app.get("/health")
async def health_check():
    try:
        client.admin.command('ping')
        return {"status": "healthy", "database": "connected"}
    except Exception as e:
        return {"status": "unhealthy", "error": str(e)}

@app.post("/expenses", response_model=dict)
async def create_expense(expense: Expense):
    """
    Disabled: this service does not create expenses.

    All expenses should be created by the main WalletSync app and stored
    directly in MongoDB. This API only reads existing data for analytics.
    """
    raise HTTPException(
        status_code=405,
        detail="Creating expenses is disabled. Use the main WalletSync app to add expenses.",
    )

@app.get("/expenses", response_model=List[Expense])
async def get_expenses(user_id: str, limit: int = 100):
    """Get expenses for a user"""
    expenses = list(db.expenses.find({"user_id": user_id}).sort("date", -1).limit(limit))
    for expense in expenses:
        expense["id"] = str(expense["_id"])
        del expense["_id"]
    return expenses

@app.post("/budgets", response_model=dict)
async def create_budget(budget: Budget):
    """
    Disabled: this service does not create budgets.

    All budgets should be created by the main WalletSync app and stored
    directly in MongoDB. This API only reads existing data for analytics.
    """
    raise HTTPException(
        status_code=405,
        detail="Creating budgets is disabled. Use the main WalletSync app to add budgets.",
    )

@app.get("/budgets", response_model=List[Budget])
async def get_budgets(user_id: str):
    """Get budgets for a user"""
    budgets = list(db.budgets.find({"user_id": user_id}))
    for budget in budgets:
        budget["id"] = str(budget["_id"])
        del budget["_id"]
    return budgets

@app.post("/recommendations/check", response_model=RecommendationResponse)
async def check_and_get_recommendations(request: RecommendationRequest, month: Optional[int] = None, year: Optional[int] = None):
    """
    Check if user has previous data for a category and return recommendations if available.
    
    Request body:
    {
        "user_id": "68a834c3f4694b11efedacd2",
        "category_id": "688c80ca990b63f0e945ecf1"
    }
    
    Response:
    - If user has previous data: returns recommendations
    - If user doesn't have previous data: returns message indicating no previous data
    """
    if not month or not year:
        # Default to next month
        next_month = datetime.now().replace(day=1) + timedelta(days=32)
        month = next_month.month
        year = next_month.year
    
    # Check if user has previous data for this category
    has_data = recommender.check_user_has_category_data(request.user_id, request.category_id)
    
    if has_data:
        # User has previous data - but if they provided budget_amount, use it (they want to set a new budget)
        if request.budget_amount and request.budget_amount > 0:
            print(f"✅ User {request.user_id} has previous data for category {request.category_id}, but provided budget_amount {request.budget_amount} - using provided amount")
            recommendations = recommender.get_recommendation_for_category(
                request.user_id, 
                request.category_id, 
                month, 
                year,
                budget_amount=request.budget_amount  # Use user's provided budget_amount
            )
        else:
            print(f"✅ User {request.user_id} has previous data for category {request.category_id} - using historical data")
            recommendations = recommender.get_recommendation_for_category(
                request.user_id, 
                request.category_id, 
                month, 
                year,
                budget_amount=None  # Use historical data if no budget_amount provided
            )
        
        if recommendations:
            return RecommendationResponse(
                has_previous_data=True,
                recommendations=recommendations,
                message=None
            )
        else:
            # User has data but no recommendations generated (edge case)
            return RecommendationResponse(
                has_previous_data=True,
                recommendations=[],
                message="User has previous data but no recommendations could be generated for this category."
            )
    elif request.budget_amount and request.budget_amount > 0:
        # User doesn't have previous data, but provided budget_amount - generate recommendation based on it
        print(f"ℹ️ User {request.user_id} does not have previous data for category {request.category_id} - using provided budget_amount")
        recommendations = recommender.get_recommendation_for_category(
            request.user_id, 
            request.category_id, 
            month, 
            year,
            request.budget_amount
        )
        
        if recommendations:
            return RecommendationResponse(
                has_previous_data=False,
                recommendations=recommendations,
                message="Recommendation generated based on provided budget amount. User does not have previous spending data for this category."
            )
        else:
            return RecommendationResponse(
                has_previous_data=False,
                recommendations=None,
                message="Could not generate recommendations even with provided budget amount."
            )
    else:
        # User doesn't have previous data and no budget_amount provided
        return RecommendationResponse(
            has_previous_data=False,
            recommendations=None,
            message=f"User does not have previous data for category_id: {request.category_id}. Please provide a budget_amount or create a budget/expenses for this category first."
        )

@app.post("/recommendations/by-name", response_model=RecommendationResponse)
async def get_recommendations_by_category_name(request: RecommendationByNameRequest, month: Optional[int] = None, year: Optional[int] = None):
    """
    Get budget recommendations by Head Category name (instead of category_id).
    This is useful for frontend integration where you only have the category name.
    
    Request body:
    {
        "user_id": "6741abd38d30ab5b7176397f",
        "category_name": "Food & Drinks",
        "budget_amount": 350.0  // optional
    }
    
    Supported Head Category names:
    - Food & Drinks
    - Shopping
    - Housing
    - Financial Expenses
    - Communication, PC
    - Vehicle
    - Transportation
    - Life & Entertainment
    - Investments
    - Income
    - Loan Payment
    - Marketing
    
    Response:
    - If user has previous data: returns recommendations based on historical data
    - If user doesn't have previous data but provided budget_amount: returns recommendations based on budget_amount
    - If user doesn't have previous data and no budget_amount: returns message asking for budget_amount
    """
    if not month or not year:
        # Default to next month
        next_month = datetime.now().replace(day=1) + timedelta(days=32)
        month = next_month.month
        year = next_month.year
    
    # Find category_id by name
    category_id = recommender._get_category_id_by_name(request.category_name)
    
    if not category_id:
        return RecommendationResponse(
            has_previous_data=False,
            recommendations=None,
            message=f"Category '{request.category_name}' not found in database. Please check the category name or create the category first."
        )
    
    # Now use the existing check endpoint logic
    has_data = recommender.check_user_has_category_data(request.user_id, category_id)
    
    if has_data:
        # User has previous data - use it for recommendations
        print(f"✅ User {request.user_id} has previous data for category '{request.category_name}' (id: {category_id}) - using historical data")
        recommendations = recommender.get_recommendation_for_category(
            request.user_id, 
            category_id, 
            month, 
            year,
            budget_amount=None  # Don't use budget_amount if user has historical data
        )
        
        if recommendations:
            return RecommendationResponse(
                has_previous_data=True,
                recommendations=recommendations,
                message=None
            )
        else:
            return RecommendationResponse(
                has_previous_data=True,
                recommendations=[],
                message="User has previous data but no recommendations could be generated for this category."
            )
    elif request.budget_amount and request.budget_amount > 0:
        # User doesn't have previous data, but provided budget_amount
        print(f"ℹ️ User {request.user_id} does not have previous data for category '{request.category_name}' (id: {category_id}) - using provided budget_amount")
        recommendations = recommender.get_recommendation_for_category(
            request.user_id, 
            category_id, 
            month, 
            year,
            request.budget_amount
        )
        
        if recommendations:
            return RecommendationResponse(
                has_previous_data=False,
                recommendations=recommendations,
                message="Recommendation generated based on provided budget amount. User does not have previous spending data for this category."
            )
        else:
            return RecommendationResponse(
                has_previous_data=False,
                recommendations=None,
                message="Could not generate recommendations even with provided budget amount."
            )
    else:
        # User doesn't have previous data and no budget_amount provided
        return RecommendationResponse(
            has_previous_data=False,
            recommendations=None,
            message=f"User does not have previous data for category '{request.category_name}'. Please provide a budget_amount to get recommendations."
        )

@app.get("/recommendations/{user_id}", response_model=List[BudgetRecommendation])
async def get_budget_recommendations(user_id: str, month: Optional[int] = None, year: Optional[int] = None):
    """
    Get smart budget recommendations for a user based on past spending behavior.
    
    Example response:
    {
        "category": "Groceries",
        "category_id": "688c80ca990b63f0e945ecf1",
        "average_expense": 3800,
        "recommended_budget": 4000,
        "reason": "Your average monthly grocery expense is Rs.3,800. We suggest setting your budget to Rs.4,000 for next month.",
        "confidence": 0.85,
        "action": "increase"
    }
    """
    if not month or not year:
        # Default to next month
        next_month = datetime.now().replace(day=1) + timedelta(days=32)
        month = next_month.month
        year = next_month.year
    
    recommendations = recommender.get_recommendations(user_id, month, year)
    return recommendations

@app.get("/category-expenses/{user_id}", response_model=List[CategoryExpense])
async def get_category_expenses(user_id: str, months: int = 3):
    """Get average expenses by category for the past N months"""
    category_expenses = recommender.get_category_averages(user_id, months)
    return category_expenses

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)





# from fastapi import FastAPI, HTTPException, Depends
# from fastapi.middleware.cors import CORSMiddleware
# from pymongo import MongoClient
# from pymongo.errors import ConnectionFailure
# import os
# from typing import List, Optional
# from datetime import datetime, timedelta
# from app.models import BudgetRecommendation, Expense, Budget, CategoryExpense
# from app.smart_recommendation import SmartBudgetRecommender

# app = FastAPI(title="Smart Budget Recommendation API", version="1.0.0")

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

# # MongoDB connection - Get from environment variable (set as secret in Hugging Face)
# MONGODB_URI = os.getenv("MONGODB_URI")
# if not MONGODB_URI:
#     raise ValueError("MONGODB_URI environment variable is required. Please set it in Hugging Face secrets.")

# try:
#     client = MongoClient(MONGODB_URI)
#     db = client.expense
#     # Test connection
#     client.admin.command('ping')
#     print("Successfully connected to MongoDB")
# except ConnectionFailure as e:
#     print(f"Failed to connect to MongoDB: {e}")
#     raise

# # Initialize Smart Budget Recommender
# recommender = SmartBudgetRecommender(db)

# @app.get("/")
# async def root():
#     return {"message": "Smart Budget Recommendation API", "status": "running"}

# @app.get("/health")
# async def health_check():
#     try:
#         client.admin.command('ping')
#         return {"status": "healthy", "database": "connected"}
#     except Exception as e:
#         return {"status": "unhealthy", "error": str(e)}

# @app.post("/expenses", response_model=dict)
# async def create_expense(expense: Expense):
#     """
#     Disabled: this service does not create expenses.

#     All expenses should be created by the main WalletSync app and stored
#     directly in MongoDB. This API only reads existing data for analytics.
#     """
#     raise HTTPException(
#         status_code=405,
#         detail="Creating expenses is disabled. Use the main WalletSync app to add expenses.",
#     )

# @app.get("/expenses", response_model=List[Expense])
# async def get_expenses(user_id: str, limit: int = 100):
#     """Get expenses for a user"""
#     expenses = list(db.expenses.find({"user_id": user_id}).sort("date", -1).limit(limit))
#     for expense in expenses:
#         expense["id"] = str(expense["_id"])
#         del expense["_id"]
#     return expenses

# @app.post("/budgets", response_model=dict)
# async def create_budget(budget: Budget):
#     """
#     Disabled: this service does not create budgets.

#     All budgets should be created by the main WalletSync app and stored
#     directly in MongoDB. This API only reads existing data for analytics.
#     """
#     raise HTTPException(
#         status_code=405,
#         detail="Creating budgets is disabled. Use the main WalletSync app to add budgets.",
#     )

# @app.get("/budgets", response_model=List[Budget])
# async def get_budgets(user_id: str):
#     """Get budgets for a user"""
#     budgets = list(db.budgets.find({"user_id": user_id}))
#     for budget in budgets:
#         budget["id"] = str(budget["_id"])
#         del budget["_id"]
#     return budgets

# @app.get("/recommendations/{user_id}", response_model=List[BudgetRecommendation])
# async def get_budget_recommendations(user_id: str, month: Optional[int] = None, year: Optional[int] = None):
#     """
#     Get smart budget recommendations for a user based on past spending behavior.
    
#     Example response:
#     {
#         "category": "Groceries",
#         "average_expense": 3800,
#         "recommended_budget": 4000,
#         "reason": "Your average monthly grocery expense is Rs.3,800. We suggest setting your budget to Rs.4,000 for next month."
#     }
#     """
#     if not month or not year:
#         # Default to next month
#         next_month = datetime.now().replace(day=1) + timedelta(days=32)
#         month = next_month.month
#         year = next_month.year
    
#     recommendations = recommender.get_recommendations(user_id, month, year)
#     return recommendations

# @app.get("/category-expenses/{user_id}", response_model=List[CategoryExpense])
# async def get_category_expenses(user_id: str, months: int = 3):
#     """Get average expenses by category for the past N months"""
#     category_expenses = recommender.get_category_averages(user_id, months)
#     return category_expenses

# if __name__ == "__main__":
#     import uvicorn
#     uvicorn.run(app, host="0.0.0.0", port=8000)