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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
547
548
549
550
"""

FastAPI Backend for Smart Parking System - AI & Payment Module

Serves AI model predictions and handles payment integration

Note: WhatsApp/External integrations handled by other teams

"""

from fastapi import FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from typing import List, Optional, Dict, Tuple
import sys
import os
from datetime import datetime
import json
from dotenv import load_dotenv
load_dotenv()
# Add parent directory to path
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from ai_model.parking_slot_classifier import ParkingSlotClassifier
from backend.payment_service import PaymentService, PaymentSimulator
from backend.database_api import DatabaseAPI, transform_parking_lots_for_ai

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

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

# Initialize services
classifier = ParkingSlotClassifier()
payment_service = None
payment_simulator = PaymentSimulator()
db_api = DatabaseAPI()

# Razorpay credentials (from environment or config)
RAZORPAY_KEY_ID = os.getenv("RAZORPAY_KEY_ID")
RAZORPAY_KEY_SECRET = os.getenv("RAZORPAY_KEY_SECRET")

# In-memory feedback cache (feedback is stored in DB, this is just for quick access)
feedback_cache = []


# Pydantic models
class ParkingSlot(BaseModel):
    slot_id: str
    latitude: float
    longitude: float
    avg_feedback: float = 3.0
    popularity_score: float = 0.5
    is_available: bool = True
    price_factor: float = 0.5
    price_per_hour: float = 50.0


class UserLocation(BaseModel):
    latitude: float
    longitude: float


class SlotRecommendationRequest(BaseModel):
    user_location: UserLocation
    slots: List[ParkingSlot]
    top_k: int = 3


class FeedbackRequest(BaseModel):
    booking_id: str
    slot_id: str
    rating: float  # 1-5
    comment: Optional[str] = None
    user_satisfaction: bool


class PaymentOrderRequest(BaseModel):
    booking_id: str
    slot_id: str
    amount: float
    duration_hours: int
    vehicle_number: str
    customer_name: str
    customer_contact: str
    customer_email: str


class PaymentVerificationRequest(BaseModel):
    order_id: str
    payment_id: str
    signature: str


# API Endpoints

@app.on_event("startup")
async def startup_event():
    """Initialize services on startup"""
    global payment_service
    
    # Load or train the AI model
    try:
        classifier.load_model('parking_model.pkl')
        print("Model loaded successfully")
    except:
        print("Training new model...")
        from ai_model.parking_slot_classifier import generate_training_data
        training_data, labels = generate_training_data(500)
        classifier.train(training_data, labels)
        classifier.save_model('parking_model.pkl')
    
    # Initialize payment service
    try:
        payment_service = PaymentService(RAZORPAY_KEY_ID, RAZORPAY_KEY_SECRET)
        print("Payment service initialized")
    except Exception as e:
        print(f"Payment service initialization failed: {e}")


@app.get("/")
async def root():
    """Health check endpoint"""
    return {
        "status": "ok",
        "message": "Smart Parking API - AI + Payment Module",
        "version": "1.0.0",
        "database": "Connected to https://aadarshsenapati.in/api/api.php"
    }


@app.get("/api/test-database")
async def test_database():
    """Test database API connection"""
    try:
        result = db_api.get_parking_lots()
        return {
            "success": result['status'] == 'success',
            "message": "Database connection test",
            "parking_lots_count": len(result.get('data', [])) if result['status'] == 'success' else 0,
            "sample_data": result.get('data', [])[:2] if result['status'] == 'success' else None
        }
    except Exception as e:
        return {
            "success": False,
            "error": str(e)
        }


@app.post("/api/recommend-slots")
async def recommend_slots(request: SlotRecommendationRequest):
    """

    Get recommended parking slots based on AI model

    Fetches real parking data from database

    """
    try:
        # Option 1: Use slots provided in request (for testing/custom data)
        if request.slots:
            slots_data = [slot.dict() for slot in request.slots]
        else:
            # Option 2: Fetch available slots from database
            db_result = db_api.get_all_available_slots()
            if db_result['status'] != 'success':
                raise HTTPException(status_code=500, detail="Failed to fetch parking slots from database")
            
            # Transform database format to AI model format
            slots_data = transform_parking_lots_for_ai(db_result.get('data', []))
            
            if not slots_data:
                return {
                    "success": False,
                    "message": "No parking slots available",
                    "recommendations": []
                }
        
        user_coords = (request.user_location.latitude, request.user_location.longitude)
        
        # Get recommendations from AI model
        recommended_slots = classifier.predict_best_slots(
            slots_data, 
            user_coords, 
            top_k=request.top_k
        )
        
        return {
            "success": True,
            "recommendations": recommended_slots,
            "count": len(recommended_slots),
            "total_available": len(slots_data)
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@app.post("/api/feedback")
async def submit_feedback(feedback: FeedbackRequest):
    """

    Submit user feedback on slot assignment

    This data is used to retrain and improve the model

    Stores in database via API

    """
    try:
        # First get the booking details to get booking ID (not UID)
        booking_result = db_api.get_booking_status(feedback.booking_id)
        
        if booking_result['status'] != 'success' or not booking_result.get('data'):
            # Cache feedback locally if booking not found
            feedback_entry = {
                "booking_uid": feedback.booking_id,
                "slot_id": feedback.slot_id,
                "rating": feedback.rating,
                "comment": feedback.comment,
                "user_satisfaction": feedback.user_satisfaction,
                "timestamp": datetime.now().isoformat()
            }
            feedback_cache.append(feedback_entry)
            
            return {
                "success": True,
                "message": "Feedback cached (booking not found in DB)",
                "cached": True
            }
        
        booking_data = booking_result['data']
        
        # Add feedback to database
        db_result = db_api.add_feedback(
            user_id=booking_data.get('user_id', 1),
            booking_id=booking_data.get('id'),
            rating=feedback.rating,
            comments=feedback.comment or ""
        )
        
        # Also cache locally for model retraining
        feedback_entry = {
            "booking_id": feedback.booking_id,
            "slot_id": feedback.slot_id,
            "rating": feedback.rating,
            "comment": feedback.comment,
            "user_satisfaction": feedback.user_satisfaction,
            "timestamp": datetime.now().isoformat()
        }
        feedback_cache.append(feedback_entry)
        
        return {
            "success": db_result['status'] == 'success',
            "message": db_result.get('message', 'Feedback submitted successfully'),
            "database": db_result['status'] == 'success'
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@app.get("/api/feedback/stats")
async def get_feedback_stats():
    """

    Get feedback statistics from cache

    """
    if not feedback_cache:
        return {
            "total_feedback": 0,
            "average_rating": 0,
            "satisfaction_rate": 0
        }
    
    total = len(feedback_cache)
    avg_rating = sum(f['rating'] for f in feedback_cache) / total
    satisfaction_rate = sum(1 for f in feedback_cache if f['user_satisfaction']) / total * 100
    
    return {
        "total_feedback": total,
        "average_rating": round(avg_rating, 2),
        "satisfaction_rate": round(satisfaction_rate, 2)
    }


@app.post("/api/payment/create-order")
async def create_payment_order(request: PaymentOrderRequest):
    """

    Create a payment order for parking booking

    Integrates with database API for booking creation

    """
    try:
        # Calculate start and end times
        from datetime import timedelta
        start_time = datetime.now()
        end_time = start_time + timedelta(hours=request.duration_hours)
        
        start_time_str = start_time.strftime("%Y-%m-%d %H:%M:%S")
        end_time_str = end_time.strftime("%Y-%m-%d %H:%M:%S")
        
        # First, ensure user is registered (or register them)
        user_result = db_api.register_user(
            name=request.customer_name,
            phone=request.customer_contact,
            email=request.customer_email
        )
        
        # Get slot ID from database (assuming slot_id in request is the slot name/identifier)
        # For now, we'll use a placeholder user_id=1 if registration fails
        user_id = 1  # This should be retrieved from user_result in production
        
        # Parse slot_id to get database ID if needed
        # If slot_id is like "A1", we need to find its DB ID
        # For now, assume slot_id is already the DB ID or can be used directly
        slot_db_id = request.slot_id
        
        # Try to parse if it's a number string
        try:
            slot_db_id = int(request.slot_id)
        except:
            # If slot_id is name like "A1", we'd need to fetch from DB
            # For now, use a default
            slot_db_id = 1
        
        # Create booking in database
        booking_result = db_api.book_slot(
            user_id=user_id,
            slot_id=slot_db_id,
            start_time=start_time_str,
            end_time=end_time_str,
            total_amount=request.amount
        )
        
        if booking_result['status'] != 'success':
            raise HTTPException(status_code=500, detail=f"Booking failed: {booking_result.get('message')}")
        
        booking_uid = booking_result.get('booking_uid')
        
        # Use simulator if payment service is not available
        use_simulator = payment_service is None
        
        if use_simulator:
            # Simulate payment
            order = {
                'success': True,
                'order_id': f'order_sim_{booking_uid}',
                'amount': request.amount,
                'currency': 'INR',
                'status': 'created',
                'mode': 'simulation'
            }
        else:
            # Real payment
            order = payment_service.create_payment_order(
                amount=request.amount,
                booking_id=booking_uid,
                notes={
                    'booking_uid': booking_uid,
                    'slot_id': request.slot_id,
                    'duration': f'{request.duration_hours} hours',
                    'vehicle_number': request.vehicle_number
                }
            )
        
        return {
            **order,
            'booking_uid': booking_uid,
            'start_time': start_time_str,
            'end_time': end_time_str
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@app.post("/api/payment/create-link")
async def create_payment_link(request: PaymentOrderRequest):
    """

    Create a payment link for WhatsApp sharing

    """
    try:
        if payment_service is None:
            # Return simulated link
            return {
                'success': True,
                'short_url': f'https://rzp.io/l/sim_{request.booking_id}',
                'mode': 'simulation',
                'message': 'This is a simulated payment link'
            }
        
        link = payment_service.create_payment_link(
            amount=request.amount,
            description=f"Parking Slot {request.slot_id} - {request.duration_hours} hours",
            customer_name=request.customer_name,
            customer_contact=request.customer_contact,
            customer_email=request.customer_email,
            booking_id=request.booking_id
        )
        
        return link
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@app.post("/api/payment/verify")
async def verify_payment(request: PaymentVerificationRequest):
    """

    Verify payment signature after payment completion

    Updates payment status in database

    """
    try:
        if payment_service is None:
            # Simulate verification
            # Update database payment status
            update_result = db_api.update_payment(
                booking_uid=request.order_id.replace('order_sim_', ''),
                payment_status='Paid',
                transaction_id=request.payment_id,
                amount=0
            )
            
            return {
                'success': True,
                'verified': True,
                'mode': 'simulation',
                'database_updated': update_result['status'] == 'success'
            }
        
        is_valid = payment_service.verify_payment_signature(
            request.order_id,
            request.payment_id,
            request.signature,
            RAZORPAY_KEY_SECRET
        )
        
        if is_valid:
            # Extract booking_uid from order_id if needed
            # Update database
            # Note: We'd need to store order_id -> booking_uid mapping
            pass
        
        return {
            'success': True,
            'verified': is_valid
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@app.post("/api/payment/simulate")
async def simulate_payment(booking_uid: str, amount: float):
    """

    Simulate a payment (for testing purposes)

    Updates database with simulated payment

    """
    try:
        # Check if booking exists in database
        booking_result = db_api.get_booking_status(booking_uid)
        
        if booking_result['status'] != 'success':
            raise HTTPException(status_code=404, detail="Booking not found")
        
        # Simulate payment
        order_id = f"order_{booking_uid}"
        simulated = payment_simulator.simulate_payment(order_id, amount)
        
        # Update booking payment status in database
        update_result = db_api.update_payment(
            booking_uid=booking_uid,
            payment_status='Paid',
            transaction_id=simulated['payment_id'],
            amount=amount
        )
        
        return {
            **simulated,
            'database_updated': update_result['status'] == 'success'
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@app.get("/api/booking/{booking_uid}")
async def get_booking(booking_uid: str):
    """

    Get booking details from database

    """
    try:
        result = db_api.get_booking_status(booking_uid)
        
        if result['status'] != 'success' or not result.get('data'):
            raise HTTPException(status_code=404, detail="Booking not found")
        
        return {
            "success": True,
            "booking": result['data']
        }
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@app.post("/api/retrain-model")
async def retrain_model():
    """

    Retrain the AI model with new feedback data from cache

    Should be called periodically or when sufficient new feedback is collected

    """
    try:
        if len(feedback_cache) < 10:
            return {
                "success": False,
                "message": f"Insufficient feedback data for retraining (need 10+, have {len(feedback_cache)})"
            }
        
        # Convert feedback to training data
        # This is simplified - in production, you'd have more sophisticated feature engineering
        training_samples = []
        labels = []
        
        for feedback in feedback_cache:
            # Create a simplified training sample
            sample = {
                'slot_id': feedback['slot_id'],
                'avg_feedback': feedback['rating'],
                'proximity_score': 0.5,  # Would come from actual data
                'popularity_score': 0.5,
                'is_available': True,
                'price_factor': 0.5
            }
            training_samples.append(sample)
            labels.append(1 if feedback['user_satisfaction'] else 0)
        
        # Retrain model
        classifier.train(training_samples, labels)
        classifier.save_model('parking_model.pkl')
        
        return {
            "success": True,
            "message": f"Model retrained with {len(training_samples)} samples",
            "samples_used": len(training_samples)
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


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