import logging
from datetime import datetime, timezone

from django.http import JsonResponse
import json
from rest_framework import viewsets
from django.shortcuts import render, redirect
from rest_framework.decorators import action
from django.contrib import messages

from .base import DummySerializer

logger = logging.getLogger(__name__)




class CloudTransferViewSet(viewsets.ModelViewSet):
    """Handles connecting and displaying cloud storage accounts (Google Drive, Dropbox, OneDrive)"""
    serializer_class = DummySerializer
    
     ##### NOW HANDLING THE FILE SELECTION WITH REAL DRIVE API ##########
    @action(detail=False, methods=['get', 'post'], url_path=r'')
    def new_transfer(self, request):
        """Step 2: File Selection with Google Drive API"""
        base_domain = request.build_absolute_uri('/')
        user = request.user
        
        if not user.is_authenticated:
            return redirect(f'{base_domain}login/')
        
        # Check if cloud is connected
        cloud_source = request.session.get('selected_cloud')
        
        if not cloud_source:
            messages.error(request, "Please connect a cloud account first")
            return redirect(f'{base_domain}transfer/cloud-connect/')
        
        context = {
            'base_domain': base_domain,
            'user': user,
            'cloud_source': cloud_source,
            'current_step': 2
        }
        
        if request.method == 'POST':
            # FIXED: Changed from 'selected_files' to 'cloud_files'
            selected_files = request.POST.getlist('cloud_files')
            
            print("Selected files for transfer:", selected_files)
            
            # Also check for uploaded files
            uploaded_files = request.POST.getlist('uploaded_files')
            print("Uploaded files for transfer:", uploaded_files)
            
            if not selected_files and not uploaded_files:
                messages.error(request, "Please select at least one file to transfer")
                return self._render_file_selection(request, context, cloud_source, user)
            
            try:
                # Create transfer order
                order = self._create_transfer_order(request, user, cloud_source, selected_files)
                request.session['current_order_id'] = str(order.id)
                request.session.modified = True
                
                return redirect(f'{base_domain}transfer/storage/')
                
            except Exception as e:
                messages.error(request, f"Error creating transfer: {str(e)}")
                print(f"Transfer creation error: {e}")
                return self._render_file_selection(request, context, cloud_source, user)
        
        # GET request - show file browser for selected cloud
        return self._render_file_selection(request, context, cloud_source, user)
        
    
    @action(detail=False, methods=['post'], url_path='upload/local')
    def upload_local_file(self, request):
        """Handle local file uploads - SIMPLE"""
        if not request.user.is_authenticated:
            return JsonResponse({'error': 'Login required'}, status=401)
        
        file_obj = request.FILES.get('file')
        if not file_obj:
            return JsonResponse({'error': 'No file provided'}, status=400)
        
        try:
            from ..models import LocalUploadedFile
            
            # Create the uploaded file record
            uploaded_file = LocalUploadedFile.objects.create(
                user=request.user,
                original_name=file_obj.name,
                file_size=file_obj.size,
                file=file_obj
            )
            
            return JsonResponse({
                'success': True,
                'file_id': str(uploaded_file.id),  # Backend UUID
                'name': uploaded_file.original_name,
                'size': uploaded_file.file_size,
                'uploaded_at': uploaded_file.uploaded_at.isoformat()
            })
            
        except Exception as e:
            logger.error(f"Upload error: {str(e)}")
            return JsonResponse({'error': str(e)}, status=500)
    

    #This renders all the files from the selected cloud service
    def _render_file_selection(self, request, context, cloud_source, user):
        """Render file selection page for specific cloud with real Google Drive API"""
        cloud_data = self._get_cloud_data(cloud_source, user) #This is where am getting the real data from the cloud services.
        context.update(cloud_data) #Contains the previous data plus the cloud data.
        return render(request, 'transfer.html', context)
    
    
    #Gets the cloud data based on the user, may vary for all the cloud providers.
    def _get_cloud_data(self, cloud_source, user):
        """Get cloud-specific data structure with real Google Drive API"""
        if cloud_source == 'google_drive':
            return self._get_google_drive_data(user)
        elif cloud_source == 'dropbox':
            return self._get_dropbox_data()
        elif cloud_source == 'onedrive':
            return self._get_onedrive_data()
        else:
            return {}
        
        
    #Gets now google drive data exactly.
    def _get_google_drive_data(self, user):
        """Google Drive API structure with real data"""
        try:
            from social_django.models import UserSocialAuth
            from google.oauth2.credentials import Credentials
            from googleapiclient.discovery import build
            from googleapiclient.errors import HttpError
            
            # Check if user has Google OAuth connected
            social_auth = UserSocialAuth.objects.filter(
                user=user, 
                provider='google-oauth2'
            ).first()
            
            if not social_auth or not social_auth.extra_data.get('access_token'):
                return {
                    'cloud_connected': False,
                    'cloud_service': 'Google Drive',
                    'user_email': 'Not connected',
                    'storage_info': {
                        'used': '0 GB',
                        'total': '0 GB',
                        'percentage': 0,
                        'available': '0 GB',
                        'quota_type': 'free'
                    },
                    'files': [],
                    'categories': [],
                    'total_files': 0,
                    'total_size': '0 GB',
                    'error': 'Please reconnect your Google Drive account'
                }
            
            # Create credentials and service
            credentials = Credentials(token=social_auth.extra_data.get('access_token'))
            service = build('drive', 'v3', credentials=credentials)
            
            # Get storage info
            about = service.about().get(fields="storageQuota,user").execute()
            storage_quota = about.get('storageQuota', {})
            user_info = about.get('user', {})
            
            used_bytes = int(storage_quota.get('usage', 0))
            total_bytes = int(storage_quota.get('limit', 0))
            used_gb = self._bytes_to_gb(used_bytes)
            total_gb = self._bytes_to_gb(total_bytes)
            usage_percentage = (used_bytes / total_bytes * 100) if total_bytes > 0 else 0
            
            # Get real files from Google Drive
            files = self._get_real_google_drive_files(service)
            
            # Get file categories
            categories = self._get_google_drive_categories(service)
            
            return {
                'cloud_connected': True,
                'cloud_service': 'Google Drive',
                'user_email': user_info.get('emailAddress', 'notconnected@gmail.com'),
                'storage_info': {
                    'used': f'{used_gb:.1f} GB',
                    'total': f'{total_gb:.0f} GB',
                    'percentage': round(usage_percentage, 1),
                    'available': f'{total_gb - used_gb:.1f} GB',
                    'quota_type': 'free' if total_gb <= 15 else 'premium'
                },
                'files': files,
                'categories': categories,
                'total_files': len(files),
                'total_size': f'{used_gb:.1f} GB'
            }
            
        except HttpError as error:
            print(f"Google Drive API error in file selection: {error}")
            return {
                'cloud_connected': False,
                'cloud_service': 'Google Drive',
                'user_email': 'Connection error',
                'storage_info': {
                    'used': '0 GB',
                    'total': '0 GB',
                    'percentage': 0,
                    'available': '0 GB',
                    'quota_type': 'free'
                },
                'files': [],
                'categories': [],
                'total_files': 0,
                'total_size': '0 GB',
                'error': 'Failed to load Google Drive files. Please try again.'
            }
        except Exception as error:
            print(f"Unexpected error in Google Drive data: {error}")
            return {
                'cloud_connected': False,
                'cloud_service': 'Google Drive',
                'user_email': 'Error',
                'storage_info': {
                    'used': '0 GB',
                    'total': '0 GB',
                    'percentage': 0,
                    'available': '0 GB',
                    'quota_type': 'free'
                },
                'files': [],
                'categories': [],
                'total_files': 0,
                'total_size': '0 GB',
                'error': 'An unexpected error occurred.'
            }

    def _get_real_google_drive_files(self, service):
        """Get real files from Google Drive API"""
        try:
            
            # Get files from Google Drive
            results = service.files().list(
                pageSize=500,  # Limit to 50 files for performance
                fields="nextPageToken, files(id, name, mimeType, size, modifiedTime, createdTime, webViewLink)",
                orderBy="modifiedTime desc"
            ).execute()
            
            
            files = results.get('files', [])
            formatted_files = []
            
            for file in files:
                # Skip app data folders and shortcuts
                if file.get('mimeType') == 'application/vnd.google-apps.shortcut':
                    continue
                    
                # Format file size
                size_bytes = int(file.get('size', 0))
                if size_bytes < 1024:
                    size_display = f"{size_bytes} B"
                elif size_bytes < 1024 * 1024:
                    size_display = f"{size_bytes / 1024:.1f} KB"
                elif size_bytes < 1024 * 1024 * 1024:
                    size_display = f"{size_bytes / (1024 * 1024):.1f} MB"
                else:
                    size_display = f"{size_bytes / (1024 * 1024 * 1024):.1f} GB"
                
                # Format modified time
                modified_time = file.get('modifiedTime')
                mod_display = "Unknown"
                if modified_time:
                    try:
                        mod_date = datetime.fromisoformat(modified_time.replace('Z', '+00:00'))
                        now = datetime.now(timezone.utc)
                        diff = now - mod_date
                        
                        if diff.days == 0:
                            if diff.seconds < 60:
                                mod_display = "Just now"
                            elif diff.seconds < 3600:
                                mod_display = f"{diff.seconds // 60} minutes ago"
                            else:
                                mod_display = f"{diff.seconds // 3600} hours ago"
                        elif diff.days == 1:
                            mod_display = "1 day ago"
                        elif diff.days < 7:
                            mod_display = f"{diff.days} days ago"
                        elif diff.days < 30:
                            mod_display = f"{diff.days // 7} weeks ago"
                        else:
                            mod_display = mod_date.strftime("%b %d, %Y")
                    except:
                        mod_display = "Unknown"
                
                # Determine file type and icon
                mime_type = file.get('mimeType', '')
                is_folder = mime_type == 'application/vnd.google-apps.folder'
                
                formatted_files.append({
                    'id': file['id'],
                    'name': file['name'],
                    'size': size_display,
                    'sizeBytes': size_bytes,
                    'mimeType': mime_type,
                    'modified_display': mod_display,
                    'folder': is_folder,
                    'webViewLink': file.get('webViewLink', ''),
                    'item_count': 'Multiple items' if is_folder else None
                })
            
            return formatted_files
            
        except Exception as e:
            print(f"Error getting Google Drive files: {e}")
            # Return empty list on error
            return []      

    def _get_google_drive_categories(self, service):
        """Get real file categories from Google Drive by analyzing actual files"""
        try:
            # Get a sample of files to analyze
            results = service.files().list(
                pageSize=100,
                fields="files(mimeType, size)",
                q="trashed=false"
            ).execute()
            
            files = results.get('files', [])
            
            # Initialize category counters
            categories = {
                'documents': {'name': 'Documents', 'count': 0, 'icon': 'file-text', 'color': 'blue'},
                'images': {'name': 'Images', 'count': 0, 'icon': 'image', 'color': 'purple'},
                'videos': {'name': 'Videos', 'count': 0, 'icon': 'video', 'color': 'red'},
                'pdfs': {'name': 'PDFs', 'count': 0, 'icon': 'file-pdf', 'color': 'red'},
                'spreadsheets': {'name': 'Sheets', 'count': 0, 'icon': 'file-excel', 'color': 'green'},
                'presentations': {'name': 'Slides', 'count': 0, 'icon': 'file-powerpoint', 'color': 'orange'},
                'audio': {'name': 'Audio', 'count': 0, 'icon': 'music', 'color': 'indigo'},
                'archives': {'name': 'Archives', 'count': 0, 'icon': 'archive', 'color': 'yellow'},
                'others': {'name': 'Others', 'count': 0, 'icon': 'file', 'color': 'gray'}
            }
            
            for file in files:
                mime_type = file.get('mimeType', '')
                
                # Categorize by MIME type
                if 'application/vnd.google-apps.document' in mime_type:
                    categories['documents']['count'] += 1
                elif 'application/vnd.google-apps.spreadsheet' in mime_type:
                    categories['spreadsheets']['count'] += 1
                elif 'application/vnd.google-apps.presentation' in mime_type:
                    categories['presentations']['count'] += 1
                elif 'application/pdf' in mime_type:
                    categories['pdfs']['count'] += 1
                elif mime_type.startswith('image/'):
                    categories['images']['count'] += 1
                elif mime_type.startswith('video/'):
                    categories['videos']['count'] += 1
                elif mime_type.startswith('audio/'):
                    categories['audio']['count'] += 1
                elif any(ext in mime_type for ext in ['zip', 'rar', 'tar', '7z']):
                    categories['archives']['count'] += 1
                elif mime_type not in ['application/vnd.google-apps.folder', 'application/vnd.google-apps.shortcut']:
                    categories['others']['count'] += 1
            
            # Filter out empty categories and return only non-zero counts
            result = []
            for category in categories.values():
                if category['count'] > 0:
                    result.append(category)
            
            # Sort by count (descending)
            result.sort(key=lambda x: x['count'], reverse=True)
            
            return result
            
        except Exception as e:
            print(f"Error analyzing Google Drive categories: {e}")
            # Fallback to basic categories
            return [
                {'name': 'Documents', 'count': 0, 'icon': 'file-text', 'color': 'blue'},
                {'name': 'Images', 'count': 0, 'icon': 'image', 'color': 'purple'},
                {'name': 'Videos', 'count': 0, 'icon': 'video', 'color': 'red'},
                {'name': 'PDFs', 'count': 0, 'icon': 'file-pdf', 'color': 'red'},
            ]

    
    #For Dropbox Dummy Data For Now.
    def _get_dropbox_data(self):
        """Dropbox API structure (dummy data)"""
        return {
            'cloud_connected': True,
            'cloud_service': 'Dropbox',
            'user_email': 'user@domain.com',
            'storage_info': {
                'used': '1.4 GB',
                'total': '2 GB',
                'percentage': 70,
                'available': '0.6 GB',
                'quota_type': 'free'
            },
            'files': self._get_dropbox_files(),
            'categories': self._get_dropbox_categories(),
            'total_files': 543,
            'total_size': '1.4 GB'
        }

    def _get_dropbox_files(self):
        """Dummy Dropbox files"""
        return [
            {
                'id': 'db_file_1',
                'name': 'Project Proposal.docx',
                'size': '2.1 MB',
                'sizeBytes': 2202009,
                'mimeType': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                'modified_display': '2 hours ago',
                'folder': False
            },
            {
                'id': 'db_file_2',
                'name': 'Vacation Photos',
                'size': '156.3 MB',
                'sizeBytes': 163877683,
                'mimeType': 'folder',
                'modified_display': '1 day ago',
                'folder': True,
                'item_count': 24
            }
        ]

    def _get_dropbox_categories(self):
        """Dummy Dropbox categories"""
        return [
            {'name': 'Documents', 'count': 45, 'icon': 'file-text', 'color': 'blue'},
            {'name': 'Photos', 'count': 123, 'icon': 'image', 'color': 'purple'},
        ]

    
    
    #For Onedrive Dummy Data For Now.
    def _get_onedrive_data(self):
        """OneDrive API structure (dummy data)"""
        return {
            'cloud_connected': True,
            'cloud_service': 'OneDrive',
            'user_email': 'user@outlook.com',
            'storage_info': {
                'used': '3.2 GB',
                'total': '5 GB',
                'percentage': 64,
                'available': '1.8 GB',
                'quota_type': 'free'
            },
            'files': self._get_onedrive_files(),
            'categories': self._get_onedrive_categories(),
            'total_files': 892,
            'total_size': '3.2 GB'
        }

    def _get_onedrive_files(self):
        """Dummy OneDrive files"""
        return [
            {
                'id': 'od_file_1',
                'name': 'Budget Spreadsheet.xlsx',
                'size': '3.8 MB',
                'sizeBytes': 3984588,
                'mimeType': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                'modified_display': '5 hours ago',
                'folder': False
            },
            {
                'id': 'od_file_2',
                'name': 'Work Documents',
                'size': '890.2 MB',
                'sizeBytes': 933232435,
                'mimeType': 'folder',
                'modified_display': '3 days ago',
                'folder': True,
                'item_count': 67
            }
        ]

    def _get_onedrive_categories(self):
        """Dummy OneDrive categories"""
        return [
            {'name': 'Documents', 'count': 234, 'icon': 'file-text', 'color': 'blue'},
            {'name': 'Pictures', 'count': 89, 'icon': 'image', 'color': 'purple'},
            {'name': 'Videos', 'count': 12, 'icon': 'video', 'color': 'red'},
        ]

    
  
    # Google Drive Files (based on Drive v3 API)
    def _get_google_drive_files(self):
        return [
            # Folders (mimeType: application/vnd.google-apps.folder)
            {
                'id': '1A2B3C4D5E6F7G8H9I0J',
                'name': 'Vacation Photos 2024',
                'mimeType': 'application/vnd.google-apps.folder',
                'size': '2.4 GB',
                'sizeBytes': 2576980377,
                'modifiedTime': '2024-06-15T10:30:00.000Z',
                'modified_display': '2 days ago',
                'icon': 'folder',
                'icon_color': 'yellow-500',
                'item_count': 342,
                'parents': ['root'],
                'webViewLink': 'https://drive.google.com/drive/folders/1A2B3C4D5E6F7G8H9I0J',
                'shared': False
            },
            # Google Docs
            {
                'id': '1aB2cD3eF4gH5iJ6kL7mN',
                'name': 'Project Proposal',
                'mimeType': 'application/vnd.google-apps.document',
                'size': '2.1 MB',
                'sizeBytes': 2202009,
                'modifiedTime': '2024-06-14T12:00:00.000Z',
                'modified_display': '1 day ago',
                'icon': 'file-alt',
                'icon_color': 'blue-500',
                'parents': ['root'],
                'webViewLink': 'https://docs.google.com/document/d/1aB2cD3eF4gH5iJ6kL7mN/edit',
                'shared': True
            },
            # Regular files
            {
                'id': '1zYxWvUtSrQpOnMlKjIhG',
                'name': 'beach_sunset.jpg',
                'mimeType': 'image/jpeg',
                'size': '4.2 MB',
                'sizeBytes': 4404019,
                'modifiedTime': '2024-06-14T16:45:00.000Z',
                'modified_display': '1 day ago',
                'icon': 'image',
                'icon_color': 'purple-500',
                'parents': ['1A2B3C4D5E6F7G8H9I0J'],
                'webViewLink': 'https://drive.google.com/file/d/1zYxWvUtSrQpOnMlKjIhG/view',
                'thumbnailLink': 'https://lh3.googleusercontent.com/d/1zYxWvUtSrQpOnMlKjIhG',
                'imageMediaMetadata': {'width': 4032, 'height': 3024}
            }
        ]

    # Dropbox Files (based on Dropbox API)
    def _get_dropbox_files(self):
        return [
            # Folders
            {
                'id': 'id:1A2B3C4D5E6F7G8H9I0J',
                'name': 'Work Projects',
                '.tag': 'folder',
                'size': '1.1 GB',
                'sizeBytes': 1181116006,
                'client_modified': '2024-06-14T09:30:00Z',
                'server_modified': '2024-06-14T09:30:00Z',
                'modified_display': '1 day ago',
                'icon': 'folder',
                'icon_color': 'blue-500',
                'path_display': '/Work Projects',
                'path_lower': '/work projects',
                'shared': False,
                'item_count': 156
            },
            # Files
            {
                'id': 'id:1aB2cD3eF4gH5iJ6kL7mN',
                'name': 'Client Presentation.pptx',
                '.tag': 'file',
                'size': '45.2 MB',
                'sizeBytes': 47395658,
                'client_modified': '2024-06-13T14:20:00Z',
                'server_modified': '2024-06-13T14:20:00Z',
                'modified_display': '2 days ago',
                'icon': 'file-powerpoint',
                'icon_color': 'orange-500',
                'path_display': '/Work Projects/Client Presentation.pptx',
                'path_lower': '/work projects/client presentation.pptx',
                'rev': '5e1b2c3d4e5f6g7h8i9j0k',
                'shared': True,
                'is_downloadable': True
            },
            {
                'id': 'id:1zYxWvUtSrQpOnMlKjIhG',
                'name': 'team_photo.jpg',
                '.tag': 'file',
                'size': '3.8 MB',
                'sizeBytes': 3984588,
                'client_modified': '2024-06-12T11:15:00Z',
                'server_modified': '2024-06-12T11:15:00Z',
                'modified_display': '3 days ago',
                'icon': 'image',
                'icon_color': 'purple-500',
                'path_display': '/Photos/team_photo.jpg',
                'path_lower': '/photos/team_photo.jpg',
                'rev': '5a4b3c2d1e0f9g8h7i6j5k',
                'shared': False,
                'is_downloadable': True
            }
        ]

    def _get_dropbox_categories(self):
        return [
            {'name': 'Images', 'count': 287, 'icon': 'images', 'color': 'purple-500'},
            {'name': 'Documents', 'count': 134, 'icon': 'file-alt', 'color': 'blue-500'},
            {'name': 'Videos', 'count': 67, 'icon': 'video', 'color': 'red-500'},
            {'name': 'PDFs', 'count': 45, 'icon': 'file-pdf', 'color': 'red-400'},
            {'name': 'Archives', 'count': 23, 'icon': 'archive', 'color': 'yellow-500'},
            {'name': 'Others', 'count': 12, 'icon': 'file', 'color': 'gray-500'}
        ]

    # OneDrive Files (based on Microsoft Graph API)
    def _get_onedrive_files(self):
        return [
            # Folders
            {
                'id': '01A2B3C4D5E6F7G8H9I0J',
                'name': 'Personal Documents',
                'folder': {'childCount': 89},
                'size': '2.1 GB',
                'sizeBytes': 2254857830,
                'lastModifiedDateTime': '2024-06-14T16:45:00Z',
                'modified_display': '1 day ago',
                'icon': 'folder',
                'icon_color': 'blue-500',
                'webUrl': 'https://1drv.ms/f/s!ABC123def456',
                'parentReference': {'path': '/drive/root:'},
                'createdDateTime': '2023-01-15T10:30:00Z'
            },
            # Office Files
            {
                'id': '01aB2cD3eF4gH5iJ6kL7mN',
                'name': 'Budget Report.xlsx',
                'file': {'mimeType': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'},
                'size': '3.2 MB',
                'sizeBytes': 3355443,
                'lastModifiedDateTime': '2024-06-13T11:20:00Z',
                'modified_display': '2 days ago',
                'icon': 'file-excel',
                'icon_color': 'green-500',
                'webUrl': 'https://1drv.ms/x/s!ABC123def456',
                'parentReference': {'path': '/drive/root:/Personal Documents'},
                'createdBy': {'user': {'displayName': 'John Doe'}},
                'shared': {'scope': 'users'}
            },
            # Regular files
            {
                'id': '01zYxWvUtSrQpOnMlKjIhG',
                'name': 'vacation_photo.jpg',
                'file': {'mimeType': 'image/jpeg'},
                'size': '5.1 MB',
                'sizeBytes': 5347737,
                'lastModifiedDateTime': '2024-06-12T14:30:00Z',
                'modified_display': '3 days ago',
                'icon': 'image',
                'icon_color': 'purple-500',
                'webUrl': 'https://1drv.ms/i/s!ABC123def456',
                'parentReference': {'path': '/drive/root:/Photos'},
                'image': {'width': 4000, 'height': 3000}
            }
        ]

    def _get_onedrive_categories(self):
        return [
            {'name': 'Images', 'count': 456, 'icon': 'images', 'color': 'purple-500'},
            {'name': 'Documents', 'count': 234, 'icon': 'file-alt', 'color': 'blue-500'},
            {'name': 'Videos', 'count': 123, 'icon': 'video', 'color': 'red-500'},
            {'name': 'Office Files', 'count': 67, 'icon': 'file-word', 'color': 'blue-400'},
            {'name': 'PDFs', 'count': 45, 'icon': 'file-pdf', 'color': 'red-400'},
            {'name': 'OneNote', 'count': 23, 'icon': 'sticky-note', 'color': 'purple-400'}
        ]

    # def _create_transfer_order(self, request, user, cloud_source, selected_files):
    #     """Create transfer order with BULK operations for performance"""
    #     from ..models import TransferOrder, FileSelection
    #     from django.db import transaction
    #     from social_django.models import UserSocialAuth
    #     #from datetime import  timezone
    #     from django.utils import timezone
        
    #     # Get the user's OAuth tokens
    #     access_token = None
    #     refresh_token = None
        
    #     if cloud_source == 'google_drive':
    #         social_auth = UserSocialAuth.objects.filter(
    #             user=user, 
    #             provider='google-oauth2'
    #         ).first()
        
    #     if social_auth:
    #         access_token = social_auth.extra_data.get('access_token')
    #         refresh_token = social_auth.extra_data.get('refresh_token')
        
    #     # Get all file info in ONE batch
    #     file_infos = self._get_files_info_batch(selected_files, cloud_source, user)
        
    #     # Calculate total size in one go
    #     total_size_bytes = sum(info.get('sizeBytes', 0) for info in file_infos.values())
        
    #     # Create order (ONE database query)
    #     order = TransferOrder.objects.create(
    #         user=user,
    #         cloud_source=cloud_source,
    #         status='file_selection_complete',
    #         total_files=len(selected_files),
    #         total_size=total_size_bytes / (1024**3),
            
    #         access_token= access_token,
    #         refresh_token=refresh_token,
    #         token_expiry=timezone.now() + timezone.timedelta(hours=1)  # Approximate expiry
    #     )
        
    #     # Prepare ALL file selections for bulk create
    #     file_selections = []
    #     for file_id in selected_files:
    #         file_info = file_infos.get(file_id)
    #         if file_info:
    #             file_selections.append(
    #                 FileSelection(
    #                     order=order,
    #                     file_id=file_id,
    #                     file_name=file_info.get('name', 'Unknown'),
    #                     file_size=file_info.get('sizeBytes', 0),
    #                     mime_type=file_info.get('mimeType') or file_info.get('file', {}).get('mimeType', ''),
    #                     cloud_source=cloud_source,
    #                     file_path=file_info.get('path_display') or file_info.get('webUrl', '')
    #                 )
    #             )
        
    #     # Bulk create ALL file selections (ONE database query instead of 300!)
    #     FileSelection.objects.bulk_create(file_selections)
        
        
    #     request.session['current_order_id'] = str(order.id)  # Convert UUID to string
    #     request.session.modified = True
        
    #     return order
    
    
    
    def _create_transfer_order(self, request, user, cloud_source, selected_files):
        """Create transfer order with BOTH cloud and local files"""
        from ..models import TransferOrder, FileSelection, LocalUploadedFile
        from django.db import transaction
        
        with transaction.atomic():
            # Parse uploaded files from request
            uploaded_files_data = []
            for uploaded_json in request.POST.getlist('uploaded_files', []):
                try:
                    data = json.loads(uploaded_json)
                    uploaded_files_data.append(data)
                except:
                    continue
            
            # Get ALL uploaded files at once
            uploaded_file_ids = [data.get('id') for data in uploaded_files_data if data.get('id')]
            uploaded_files = LocalUploadedFile.objects.filter(
                id__in=uploaded_file_ids,
                user=user
            )
            
            # Calculate totals
            total_files = len(selected_files) + len(uploaded_files)
            total_size_bytes = 0
            
            # Create order
            order = TransferOrder.objects.create(
                user=user,
                cloud_source=cloud_source,
                status='file_selection_complete',
                total_files=total_files,
                total_size=0  # Will update after
            )
            
            # Link uploaded files to this order
            uploaded_files.update(transfer_order=order)
            
            # Prepare ALL file selections
            file_selections = []
            
            # 1. CLOUD FILES (from Google Drive, etc.)
            cloud_file_infos = self._get_files_info_batch(selected_files, cloud_source, user)
            
            for file_id in selected_files:
                file_info = cloud_file_infos.get(file_id)
                if file_info:
                    file_selections.append(
                        FileSelection(
                            order=order,
                            file_id=file_id,
                            file_name=file_info.get('name', 'Unknown'),
                            file_size=file_info.get('sizeBytes', 0),
                            mime_type=file_info.get('mimeType', ''),
                            cloud_source=cloud_source,
                            file_path=file_info.get('path_display') or file_info.get('webUrl', '')
                        )
                    )
                    total_size_bytes += file_info.get('sizeBytes', 0)
            
            # 2. LOCAL UPLOADED FILES
            for uploaded_file in uploaded_files:
                file_selections.append(
                    FileSelection(
                        order=order,
                        file_id=str(uploaded_file.id),  # Use uploaded file's UUID
                        file_name=uploaded_file.original_name,
                        file_size=uploaded_file.file_size,
                        mime_type='',  # Could extract from filename
                        cloud_source='local_upload',
                        file_path=uploaded_file.file.url,  # URL for admin
                        local_file=uploaded_file  # Link to the uploaded file
                    )
                )
                total_size_bytes += uploaded_file.file_size
            
            # Save everything
            FileSelection.objects.bulk_create(file_selections)
            
            # Update order with total size
            order.total_size = total_size_bytes / (1024 ** 3)  # Convert to GB
            order.save()
            
            request.session['current_order_id'] = str(order.id)
            request.session.modified = True
            
            return order
        
        
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    

    def _get_files_info_batch(self, file_ids, cloud_source, user):
        """Get file information in BATCH instead of one-by-one"""
        cloud_data = self._get_cloud_data(cloud_source, user)
        files = cloud_data.get('files', [])
        
        # Create a lookup dictionary for O(1) access
        file_lookup = {file['id']: file for file in files}
        
        # Return only the files that were selected
        return {file_id: file_lookup.get(file_id) for file_id in file_ids}
    
    def _get_file_info(self, file_id, cloud_source, user):
        """Get file information from mock data"""
        cloud_data = self._get_cloud_data(cloud_source,user)
        files = cloud_data.get('files', [])
        for file in files:
            if file['id'] == file_id:
                return file
        return None
    
    
    def _bytes_to_gb(self, bytes_value):
        """Convert bytes to gigabytes"""
        return bytes_value / (1024 ** 3)

