File size: 31,134 Bytes
97f32ec
 
 
 
 
 
 
 
 
 
 
 
 
 
25039bc
 
 
 
 
97f32ec
 
 
25039bc
 
 
97f32ec
ffedc01
97f32ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25039bc
 
 
 
 
 
4927596
 
 
 
25039bc
6b6a264
25039bc
ffedc01
 
 
 
 
 
 
25039bc
6b6a264
4927596
6b6a264
ffedc01
6b6a264
5528998
116dc2c
6b6a264
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4927596
6b6a264
 
 
 
 
 
5528998
 
6b6a264
 
5528998
6b6a264
4927596
6b6a264
ffedc01
25039bc
 
 
97f32ec
25039bc
116dc2c
85ff68e
 
 
25039bc
85ff68e
 
 
25039bc
 
 
116dc2c
85ff68e
 
25039bc
 
 
85ff68e
25039bc
 
116dc2c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25039bc
116dc2c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25039bc
 
 
116dc2c
 
 
 
 
25039bc
116dc2c
85ff68e
 
25039bc
 
 
116dc2c
4927596
 
116dc2c
 
 
 
 
 
 
 
 
 
 
 
4927596
116dc2c
 
 
 
 
 
 
 
 
 
 
 
 
25039bc
 
97f32ec
25039bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116dc2c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25039bc
 
 
 
 
 
 
 
 
 
 
 
 
97f32ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d3038b
97f32ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fd9b2eb
97f32ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fd9b2eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97f32ec
 
fd9b2eb
 
97f32ec
fd9b2eb
 
 
 
 
 
97f32ec
fd9b2eb
 
 
97f32ec
fd9b2eb
 
 
 
 
 
 
 
97f32ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fd9b2eb
97f32ec
 
 
 
 
 
 
 
 
 
 
 
fd9b2eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97f32ec
fd9b2eb
 
97f32ec
fd9b2eb
 
 
 
97f32ec
fd9b2eb
97f32ec
 
 
 
 
 
 
 
 
 
 
 
 
fd9b2eb
97f32ec
 
 
 
 
 
 
 
 
 
 
 
 
fd9b2eb
 
 
97f32ec
fd9b2eb
 
 
97f32ec
fd9b2eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97f32ec
fd9b2eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97f32ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from django.shortcuts import get_object_or_404
from rest_framework import status
from rest_framework.decorators import api_view, permission_classes
from django.views.decorators.csrf import csrf_exempt
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated, AllowAny
from django.views.decorators.clickjacking import xframe_options_exempt
from rest_framework_simplejwt.tokens import AccessToken
from rest_framework_simplejwt.exceptions import TokenError
from rest_framework_simplejwt.authentication import JWTAuthentication
from rest_framework.exceptions import AuthenticationFailed
from django.contrib.auth import get_user_model
from auth_app.utils import IsAdmin
from auth_app.models import User
from .models import PaperWork, Invitation
from .serializers import (
    PaperWorkSerializer, PaperWorkDeadlineUpdateSerializer,
    InvitationSerializer, AcceptInvitationSerializer
)
from auth_app.serializers import UserRegistrationSerializer, UserSerializer
from api.models import Version
from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
from django.utils import timezone
import os
import requests
import zipfile
import base64
from django.http import FileResponse, Http404, JsonResponse, HttpResponseNotFound

def _auth_from_query_token(request):
    token = getattr(request, "query_params", {}).get("token") or request.GET.get("token")
    if not token:
        return None
    try:
        decoded = AccessToken(token)
        user_id = decoded.get("user_id")
        if not user_id:
            return None
        User = get_user_model()
        user = User.objects.get(id=user_id)
        request.user = user
        return user
    except TokenError as e:
        print(f"Token authentication error: {e}")
        return None
    except get_user_model().DoesNotExist:
        return None
    except Exception as e:
        print(f"Unexpected token parse error: {e}")
        return None


def _build_invite_link(token: str) -> str:
    # Use FRONTEND_URL so the user clicks a frontend route which then POSTs to API
    return f"{settings.FRONTEND_URL}/accept-invite/{token}"


import logging

logger = logging.getLogger(__name__)

def _send_invite_email(email: str, invite_link: str, inviter: str = None):
    """Send an invitation email using Resend API."""
    subject = "You're invited to join Project Management System"
    html_content = render_to_string(
        "emails/invite.html", {"invite_link": invite_link, "inviter": inviter}
    )
    text_content = (
        f"You have been invited to join the Project Management System.\n\n"
        f"Click the link to accept: {invite_link}"
    )

    # Try Resend API first
    try:
        api_key = getattr(settings, 'RESEND_API_KEY', None)
        if not api_key:
            raise Exception("RESEND_API_KEY not set in settings.")

        from_email = getattr(settings, 'FROM_EMAIL', 'PMS <onboarding@resend.dev>')
        
        # Resend API payload
        payload = {
            "from": from_email,
            "to": [email],
            "subject": subject,
            "html": html_content,
            "text": text_content
        }
        
        headers = {
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json"
        }
        
        response = requests.post(
            "https://api.resend.com/emails",
            json=payload,
            headers=headers
        )
        
        if response.status_code not in (200, 201):
            logger.error(f"Resend API error {response.status_code}: {response.text}")
            raise Exception(f"Resend API error {response.status_code}: {response.text}")
        
        logger.info(f"Invitation email sent successfully to {email} via Resend API")
        return {
            "status_code": response.status_code,
            "body": response.text,
            "method": "resend_api"
        }
        
    except Exception as e:
        logger.error(f"Failed to send invitation email to {email}: {str(e)}")
        raise

@csrf_exempt
@api_view(["POST"])
@permission_classes([IsAuthenticated, IsAdmin])
def invite_user(request):
    """Admin endpoint to create Invitation and send email with retry support"""
    logger.info(f"Invite user request from {request.user.username} ({request.user.role})")
    logger.info(f"Request data: {request.data}")
    
    serializer = InvitationSerializer(data=request.data)
    if not serializer.is_valid():
        logger.error(f"Serializer validation failed: {serializer.errors}")
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    email = serializer.validated_data["email"].lower()
    role = serializer.validated_data.get("role", "RESEARCHER")
    force_resend = serializer.validated_data.get("force_resend", False)
    
    logger.info(f"Processing invitation for {email} with role {role}")

    # Prevent inviting an email that already has a user
    if User.objects.filter(email__iexact=email).exists():
        logger.warning(f"Attempted to invite existing user: {email}")
        return Response({"error": "A user with this email already exists."}, status=status.HTTP_400_BAD_REQUEST)

    # Handle existing invitations with retry logic
    try:
        invitation = Invitation.objects.get(email=email)
        created = False
        
        # If invitation was already accepted but user doesn't exist (data inconsistency), mark as not accepted
        if invitation.is_accepted and not User.objects.filter(email__iexact=email).exists():
            invitation.is_accepted = False
            invitation.save()
            logger.info(f"Reset accepted status for invitation {email} - user doesn't exist")
            
    except Invitation.DoesNotExist:
        invitation = Invitation.objects.create(
            email=email, 
            role=role, 
            invited_by=request.user
        )
        created = True
    
    if not created:
        # Check if we can send another email
        if not force_resend and not invitation.can_send_email():
            reason = "already accepted" if invitation.is_accepted else "expired" if invitation.is_expired() else "maximum attempts reached"
            logger.warning(f"Cannot send invitation to {email}: {reason}")
            return Response({
                "error": f"Cannot send invitation: {reason}",
                "details": {
                    "attempts": invitation.email_attempts,
                    "last_attempt": invitation.last_email_attempt,
                    "email_sent_successfully": invitation.email_sent_successfully,
                    "expires_at": invitation.expires_at,
                    "is_expired": invitation.is_expired()
                }
            }, status=status.HTTP_400_BAD_REQUEST)
        
        # Update invitation details if needed
        invitation.role = role
        invitation.invited_by = request.user
        invitation.is_accepted = False
        
        # Extend expiry if it's expired or about to expire
        if invitation.is_expired() or invitation.time_remaining() < timezone.timedelta(hours=24):
            invitation.expires_at = timezone.now() + timezone.timedelta(hours=48)
            
        invitation.save()
        logger.info(f"Updated existing invitation for {email} (attempt #{invitation.email_attempts + 1})")
    else:
        logger.info(f"Created new invitation for {email}")

    invite_link = _build_invite_link(invitation.token)

    # Send email with error handling and attempt tracking
    try:
        _send_invite_email(email, invite_link, inviter=getattr(request.user, "username", None))
        invitation.record_email_attempt(success=True)
        logger.info(f"Successfully sent invitation email to {email} (attempt #{invitation.email_attempts})")
        
        return Response({
            "message": "Invitation sent successfully.",
            "details": {
                "attempt_number": invitation.email_attempts,
                "remaining_attempts": max(0, 5 - invitation.email_attempts),
                "expires_at": invitation.expires_at
            }
        }, status=status.HTTP_201_CREATED)
        
    except Exception as e:
        invitation.record_email_attempt(success=False)
        logger.error(f"Failed to send invitation email to {email} (attempt #{invitation.email_attempts}): {str(e)}")
        
        # Don't delete the invitation on failure - allow retries
        return Response({
            "error": "Failed to send invitation email. You can try again.",
            "details": {
                "attempt_number": invitation.email_attempts,
                "remaining_attempts": max(0, 5 - invitation.email_attempts),
                "can_retry": invitation.can_send_email(),
                "error_message": str(e)
            }
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@csrf_exempt
@api_view(["POST"])
@permission_classes([AllowAny])
def accept_invite(request, token):
    """User endpoint to accept invite and create their account"""
    # Validate invitation
    try:
        invitation = Invitation.objects.get(token=token, is_accepted=False)
    except Invitation.DoesNotExist:
        return Response({"error": "Invalid or already used invitation."}, status=status.HTTP_400_BAD_REQUEST)

    if invitation.is_expired():
        return Response({"error": "Invitation has expired."}, status=status.HTTP_400_BAD_REQUEST)

    serializer = AcceptInvitationSerializer(data=request.data)
    serializer.is_valid(raise_exception=True)

    username = serializer.validated_data["username"]
    password = serializer.validated_data["password"]
    first_name = serializer.validated_data.get("first_name", "")
    last_name = serializer.validated_data.get("last_name", "")

    # Create the user
    user = User.objects.create_user(username=username, email=invitation.email, password=password)
    user.first_name = first_name
    user.last_name = last_name

    # Set role from invitation
    user.role = invitation.role
    user.save()

    # Mark invitation accepted
    invitation.is_accepted = True
    invitation.save()

    return Response({"message": "User created successfully."}, status=status.HTTP_201_CREATED)


@csrf_exempt
@api_view(["POST"])
@permission_classes([IsAuthenticated, IsAdmin])
def retry_invitation(request, token):
    """Admin endpoint to retry sending an invitation email"""
    try:
        invitation = Invitation.objects.get(token=token, is_accepted=False)
    except Invitation.DoesNotExist:
        return Response({"error": "Invitation not found or already accepted."}, status=status.HTTP_404_NOT_FOUND)
    
    logger.info(f"Retry invitation request for {invitation.email} from {request.user.username}")
    
    # Check if we can send another email
    if not invitation.can_send_email():
        reason = "expired" if invitation.is_expired() else "maximum attempts reached"
        logger.warning(f"Cannot retry invitation to {invitation.email}: {reason}")
        return Response({
            "error": f"Cannot retry invitation: {reason}",
            "details": {
                "attempts": invitation.email_attempts,
                "last_attempt": invitation.last_email_attempt,
                "email_sent_successfully": invitation.email_sent_successfully,
                "expires_at": invitation.expires_at,
                "is_expired": invitation.is_expired()
            }
        }, status=status.HTTP_400_BAD_REQUEST)
    
    invite_link = _build_invite_link(invitation.token)
    
    # Send email with error handling and attempt tracking
    try:
        _send_invite_email(invitation.email, invite_link, inviter=getattr(request.user, "username", None))
        invitation.record_email_attempt(success=True)
        logger.info(f"Successfully retried invitation email to {invitation.email} (attempt #{invitation.email_attempts})")
        
        return Response({
            "message": "Invitation retry sent successfully.",
            "details": {
                "attempt_number": invitation.email_attempts,
                "remaining_attempts": max(0, 5 - invitation.email_attempts),
                "expires_at": invitation.expires_at
            }
        }, status=status.HTTP_200_OK)
        
    except Exception as e:
        invitation.record_email_attempt(success=False)
        logger.error(f"Failed to retry invitation email to {invitation.email} (attempt #{invitation.email_attempts}): {str(e)}")
        
        return Response({
            "error": "Failed to retry invitation email.",
            "details": {
                "attempt_number": invitation.email_attempts,
                "remaining_attempts": max(0, 5 - invitation.email_attempts),
                "can_retry": invitation.can_send_email(),
                "error_message": str(e)
            }
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(["GET"])
@permission_classes([IsAuthenticated, IsAdmin])
def pending_invitations(request):
    """Admin endpoint to list all pending invitations with retry status"""
    invitations = Invitation.objects.filter(is_accepted=False).order_by('-created_at')
    
    invitation_data = []
    for invitation in invitations:
        invitation_data.append({
            "token": str(invitation.token),
            "email": invitation.email,
            "role": invitation.role,
            "invited_by": invitation.invited_by.username if invitation.invited_by else None,
            "created_at": invitation.created_at,
            "expires_at": invitation.expires_at,
            "is_expired": invitation.is_expired(),
            "time_remaining": str(invitation.time_remaining()),
            "email_attempts": invitation.email_attempts,
            "last_email_attempt": invitation.last_email_attempt,
            "email_sent_successfully": invitation.email_sent_successfully,
            "can_retry": invitation.can_send_email(),
            "remaining_attempts": max(0, 5 - invitation.email_attempts)
        })
    
    return Response({
        "invitations": invitation_data,
        "total_count": len(invitation_data)
    })


@api_view(["GET"])
@permission_classes([AllowAny])
def verify_invite(request, token):
    """Optional endpoint for the frontend to check token validity before rendering the sign up form."""
    try:
        invitation = Invitation.objects.get(token=token, is_accepted=False)
    except Invitation.DoesNotExist:
        return Response({"valid": False, "reason": "not_found"}, status=status.HTTP_404_NOT_FOUND)

    if invitation.is_expired():
        return Response({"valid": False, "reason": "expired"}, status=status.HTTP_400_BAD_REQUEST)

    return Response({"valid": True, "email": invitation.email, "expires_at": invitation.expires_at})

@api_view(['PATCH'])
@permission_classes([IsAuthenticated, IsAdmin])
@csrf_exempt
def update_paperwork_deadline(request, id):
    
    paperwork = get_object_or_404(PaperWork, id=id)
    
    serializer = PaperWorkDeadlineUpdateSerializer(paperwork, data=request.data, partial=True)
    if serializer.is_valid():
        serializer.save()
        return Response(PaperWorkSerializer(paperwork).data)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

@api_view(['PATCH'])
@permission_classes([IsAuthenticated, IsAdmin])
@csrf_exempt
def update_user_status(request, username):
    
    user = get_object_or_404(User, username=username)
    
    if 'status' not in request.data:
        return Response({'error': 'Status field is required'}, status=status.HTTP_400_BAD_REQUEST)
    
    status_value = request.data['status']
    if status_value not in dict(User.STATUS_CHOICES):
        return Response({'error': 'Invalid status value'}, status=status.HTTP_400_BAD_REQUEST)
    
    user.status = status_value
    user.save()
    
    return Response(UserSerializer(user).data)

@api_view(['POST'])
@permission_classes([IsAuthenticated, IsAdmin])
@csrf_exempt
def assign_paperwork(request):
    
    serializer = PaperWorkSerializer(data=request.data)
    if serializer.is_valid():
        # Get the researcher
        researcher_id = serializer.validated_data.pop('researcher_id')
        researcher = get_object_or_404(User, id=researcher_id, role='RESEARCHER')
        
        # Create the paperwork
        paperwork = serializer.save(researcher=researcher)
        
        return Response(PaperWorkSerializer(paperwork).data, status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

@api_view(['GET'])
@permission_classes([IsAuthenticated, IsAdmin])
def users_list(request):
    """Endpoint to list all users except admins in the system. Only accessible to admins."""
    users = User.objects.exclude(role='ADMIN').only('id', 'username', 'email', 'role', 'status')
    serializer = UserSerializer(users, many=True)
    return Response(serializer.data)

@api_view(['GET'])
@permission_classes([AllowAny])  # was IsAuthenticated
@xframe_options_exempt            # allow rendering in <iframe>
def view_paperwork_file(request, paperwork_id, version_no, file_type):
    # 1) Try auth from ?token=...
    _auth_from_query_token(request)

    # 2) If still unauthenticated, reject (works for either header or query-token)
    if not request.user or not request.user.is_authenticated:
        return Response({'detail': 'Authentication credentials were not provided.'},
                        status=status.HTTP_401_UNAUTHORIZED)

    # Existing lookup
    try:
        version = Version.objects.get(
            paperwork__id=paperwork_id, version_no=version_no
        )
    except Version.DoesNotExist:
        raise Http404("Version not found")

    # 3) Object-level authorization: admin OR the assigned researcher
    is_admin = getattr(request.user, 'role', '').upper() == 'ADMIN'
    is_owner = getattr(version.paperwork, 'researcher_id', None) == getattr(request.user, 'id', None)
    if not (is_admin or is_owner):
        return Response({'detail': 'Forbidden'}, status=status.HTTP_403_FORBIDDEN)

    # Get the file path from the version based on file type
    file_path = None
    if file_type == 'pdf':
        file_path = version.pdf_path
    elif file_type == 'tex':
        file_path = version.latex_path
    elif file_type == 'zip':
        file_path = version.python_path
    elif file_type == 'docx':
        file_path = version.docx_path
    else:
        return Response({'error': 'Invalid file type'}, status=status.HTTP_400_BAD_REQUEST)

    if not file_path:
        raise Http404(f"{file_type.capitalize()} file not found for this version")

    # Use Django's default storage to access files from Backblaze B2
    from django.core.files.storage import default_storage
    from django.http import HttpResponse
    import mimetypes
    
    try:
        # Check if file exists in storage (Backblaze B2)
        if not default_storage.exists(file_path):
            logger.error(f"File not found in B2 storage: {file_path}")
            raise Http404("File not found in storage")
        
        # Get the file from storage
        file_obj = default_storage.open(file_path, 'rb')
        
        # Determine content type
        content_type, _ = mimetypes.guess_type(file_path)
        if not content_type:
            content_type = 'application/octet-stream'
        
        # Create response with file content
        response = HttpResponse(file_obj.read(), content_type=content_type)
        
        # Set filename for download
        filename = os.path.basename(file_path) or f"paper.{file_type}"
        disposition = 'attachment' if request.GET.get('download') else 'inline'
        response['Content-Disposition'] = f'{disposition}; filename="{filename}"'
        
        file_obj.close()
        return response
        
    except Exception as e:
        logger.error(f"Error accessing file {file_path} from B2 storage: {str(e)}")
        # Fallback: try local file system as backup
        filename = os.path.basename(file_path) if file_path else f"paper.{file_type}"
        version_str = f"v{version_no}"

        storage_full_path = os.path.join(
            settings.MEDIA_ROOT, file_path
        )

        if os.path.exists(storage_full_path):
            response = FileResponse(open(storage_full_path, 'rb'))
            disposition = 'attachment' if request.GET.get('download') else 'inline'
            response['Content-Disposition'] = f'{disposition}; filename="{filename}"'
            return response

        logger.error(f"File not found in both B2 storage and local filesystem: {file_path}")
        raise Http404("File not found")

@api_view(['GET'])
@permission_classes([IsAuthenticated, IsAdmin])
def user_detail(request, user_id):
    """Endpoint to get a specific user by ID. Only accessible to admins."""
    from django.shortcuts import get_object_or_404
    user = get_object_or_404(User, id=user_id)
    serializer = UserSerializer(user)
    return Response(serializer.data)

@api_view(['GET'])
@permission_classes([AllowAny])  # was [IsAuthenticated, IsAdmin]
@xframe_options_exempt            # allow rendering in <iframe>
def view_zip_contents(request, paperwork_id, version_no):
    # 1) Try auth from ?token=
    _auth_from_query_token(request)

    # 2) Require auth
    if not request.user or not request.user.is_authenticated:
        return Response({'detail': 'Authentication credentials were not provided.'},
                        status=status.HTTP_401_UNAUTHORIZED)

    # Get version from database
    try:
        version = Version.objects.get(
            paperwork__id=paperwork_id, version_no=version_no
        )
    except Version.DoesNotExist:
        raise Http404("Version not found")

    is_admin = getattr(request.user, 'role', '').upper() == 'ADMIN'
    is_owner = getattr(version.paperwork, 'researcher_id', None) == getattr(request.user, 'id', None)
    if not (is_admin or is_owner):
        return Response({'detail': 'Forbidden'}, status=status.HTTP_403_FORBIDDEN)

    # Get the python ZIP file path
    if not version.python_path:
        raise Http404("ZIP file not found for this version")

    # Use Django's default storage to access ZIP from Backblaze B2
    from django.core.files.storage import default_storage
    import tempfile
    
    try:
        # Check if file exists in storage
        if not default_storage.exists(version.python_path):
            raise Http404("ZIP file not found in storage")
        
        # Download ZIP file to temporary location for processing
        with default_storage.open(version.python_path, 'rb') as zip_file:
            contents = []
            with zipfile.ZipFile(zip_file, 'r') as z:
                for name in z.namelist():
                    contents.append(name)
            
            return JsonResponse({"files": contents})
    
    except Exception as e:
        logger.error(f"Error accessing ZIP file {version.python_path} from B2 storage: {str(e)}")
        # Fallback to local file system
        version_str = f"v{version_no}"
        zip_path = os.path.join(
            settings.MEDIA_ROOT,
            settings.PYTHON_STORAGE_PATH,
            str(paperwork_id),
            version_str,
            "code.zip"
        )

        if not os.path.exists(zip_path):
            raise Http404("ZIP file not found")

        contents = []
        with zipfile.ZipFile(zip_path, 'r') as z:
            for name in z.namelist():
                contents.append(name)

        return JsonResponse({"files": contents})

@api_view(['GET'])
@permission_classes([AllowAny])
@xframe_options_exempt
def view_zip_file_content(request, paperwork_id, version_no, file_path):
    # 1) Try auth from ?token=...
    _auth_from_query_token(request)

    # 2) If still unauthenticated, reject
    if not request.user or not request.user.is_authenticated:
        return Response({'detail': 'Authentication credentials were not provided.'},
                        status=status.HTTP_401_UNAUTHORIZED)

    # Get version from database
    try:
        version = Version.objects.get(
            paperwork__id=paperwork_id, version_no=version_no
        )
    except Version.DoesNotExist:
        raise Http404("Version not found")

    # 3) Object-level authorization: admin OR the assigned researcher
    is_admin = getattr(request.user, 'role', '').upper() == 'ADMIN'
    is_owner = getattr(version.paperwork, 'researcher_id', None) == getattr(request.user, 'id', None)
    if not (is_admin or is_owner):
        return Response({'detail': 'Forbidden'}, status=status.HTTP_403_FORBIDDEN)

    # Get the python ZIP file path
    if not version.python_path:
        raise Http404("ZIP file not found for this version")

    # Use Django's default storage to access ZIP from Backblaze B2
    from django.core.files.storage import default_storage
    
    try:
        # Check if file exists in storage
        if not default_storage.exists(version.python_path):
            raise Http404("ZIP file not found in storage")
        
        # Access ZIP file from storage
        with default_storage.open(version.python_path, 'rb') as zip_file:
            with zipfile.ZipFile(zip_file, 'r') as z:
                # Check if the file exists in the ZIP
                if file_path not in z.namelist():
                    return Response({'error': 'File not found in ZIP archive'}, status=status.HTTP_404_NOT_FOUND)
                
                # Determine content type based on file extension
                file_extension = file_path.split('.')[-1].lower() if '.' in file_path else ''
                content_type = 'text/plain'
                is_binary = False
                
                # Text-based files
                if file_extension in ['py']:
                    content_type = 'text/x-python'
                elif file_extension in ['ipynb']:
                    content_type = 'application/json'
                # Image files
                elif file_extension in ['png']:
                    content_type = 'image/png'
                    is_binary = True
                elif file_extension in ['jpg', 'jpeg']:
                    content_type = 'image/jpeg'
                    is_binary = True
                
                # Handle binary files (images)
                if is_binary:
                    file_content = base64.b64encode(z.read(file_path)).decode('utf-8')
                    return Response({
                        'content': file_content, 
                        'content_type': content_type,
                        'is_binary': True
                    })
                else:
                    # Handle text files
                    file_content = z.read(file_path).decode('utf-8', errors='replace')
                    return Response({
                        'content': file_content, 
                        'content_type': content_type,
                        'is_binary': False
                    })
    
    except Exception as e:
        logger.error(f"Error accessing ZIP file {version.python_path} from B2 storage: {str(e)}")
        # Fallback to local file system
        version_str = f"v{version_no}"
        zip_path = os.path.join(
            settings.MEDIA_ROOT,
            settings.PYTHON_STORAGE_PATH,
            str(paperwork_id),
            version_str,
            "code.zip"
        )

        if not os.path.exists(zip_path):
            raise Http404("ZIP file not found")

        try:
            with zipfile.ZipFile(zip_path, 'r') as z:
                # Check if the file exists in the ZIP
                if file_path not in z.namelist():
                    return Response({'error': 'File not found in ZIP archive'}, status=status.HTTP_404_NOT_FOUND)
                
                # Determine content type based on file extension
                file_extension = file_path.split('.')[-1].lower() if '.' in file_path else ''
                content_type = 'text/plain'
                is_binary = False
                
                # Text-based files
                if file_extension in ['py']:
                    content_type = 'text/x-python'
                elif file_extension in ['ipynb']:
                    content_type = 'application/json'
                # Image files
                elif file_extension in ['png']:
                    content_type = 'image/png'
                    is_binary = True
                elif file_extension in ['jpg', 'jpeg']:
                    content_type = 'image/jpeg'
                    is_binary = True
                
                # Handle binary files (images)
                if is_binary:
                    file_content = base64.b64encode(z.read(file_path)).decode('utf-8')
                    return Response({
                        'content': file_content, 
                        'content_type': content_type,
                        'is_binary': True
                    })
                else:
                    # Handle text files
                    file_content = z.read(file_path).decode('utf-8', errors='replace')
                    return Response({
                        'content': file_content, 
                        'content_type': content_type,
                        'is_binary': False
                    })
        except Exception as e:
            return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    
def download_paperwork_file(request, pk, version_no, file_type):
    # Try token auth first
    token = request.GET.get("token")
    if token:
        jwt_auth = JWTAuthentication()
        try:
            validated_token = jwt_auth.get_validated_token(token)
            user = jwt_auth.get_user(validated_token)
            request.user = user
        except Exception:
            raise AuthenticationFailed("Invalid token")

    if not request.user or not request.user.is_authenticated:
        return Response({"detail": "Authentication credentials were not provided."}, status=401)

    paperwork = get_object_or_404(PaperWork, pk=pk)
    version = get_object_or_404(paperwork.versions, version_no=version_no)
    # Map file_type string to the correct model field
    path_map = {
        "pdf": getattr(version, "pdf_path", None),
        "docx": getattr(version, "docx_path", None),
        "tex": getattr(version, "latex_path", None),
        "python": getattr(version, "python_path", None),
        "zip": getattr(version, "zip_path", None),
    }

    rel_path = path_map.get(file_type)
    if not rel_path:
        return HttpResponseNotFound(f"Unsupported file type: {file_type}")

    # Build absolute path
    file_path = os.path.join(settings.MEDIA_ROOT, rel_path)

    if not os.path.exists(file_path):
        return HttpResponseNotFound("File not found on disk")

    response = FileResponse(open(file_path, "rb"), content_type="application/octet-stream")
    response["Content-Disposition"] = f"attachment; filename={os.path.basename(file_path)}"
    return response