﻿# app/services/drive_oauth_service.py
import os
import pickle
from google_auth_oauthlib.flow import Flow
from google.auth.transport.requests import Request
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload
from flask import current_app, session, request, redirect, url_for

class DriveOAuthService:
    def __init__(self):
        self.scopes = ['https://www.googleapis.com/auth/drive.file']
        self.credentials_file = 'app/config/oauth_credentials.json'
        
    def get_authorization_url(self):
        """Generate OAuth authorization URL"""
        flow = Flow.from_client_secrets_file(
            self.credentials_file, scopes=self.scopes)
        flow.redirect_uri = request.url_root + 'oauth2callback'
        authorization_url, state = flow.authorization_url(
            access_type='offline', include_granted_scopes='true')
        session['state'] = state
        return authorization_url
        
    def handle_oauth_callback(self, authorization_code):
        """Handle OAuth callback and store credentials"""
        flow = Flow.from_client_secrets_file(
            self.credentials_file, scopes=self.scopes, state=session['state'])
        flow.redirect_uri = request.url_root + 'oauth2callback'
        flow.fetch_token(code=authorization_code)
        
        # Store credentials for reuse
        creds_data = flow.credentials
        with open('drive_token.pickle', 'wb') as token:
            pickle.dump(creds_data, token)
        return True
        
    def upload_signed_contract(self, pdf_path, contract_id):
        """Upload signed contract PDF to Google Drive"""
        try:
            # Load stored credentials
            creds = None
            if os.path.exists('drive_token.pickle'):
                with open('drive_token.pickle', 'rb') as token:
                    creds = pickle.load(token)
                    
            if not creds or not creds.valid:
                if creds and creds.expired and creds.refresh_token:
                    creds.refresh(Request())
                else:
                    return None  # Need to re-authorize
                    
            service = build('drive', 'v3', credentials=creds)
            
            file_metadata = {
                'name': f'Contract_{contract_id}_Signed.pdf'
            }
            
            media = MediaFileUpload(pdf_path, mimetype='application/pdf')
            file = service.files().create(
                body=file_metadata, media_body=media, fields='id,webViewLink'
            ).execute()
            
            current_app.logger.info(f"Contract {contract_id} uploaded to Drive")
            return file.get('webViewLink')
            
        except Exception as e:
            current_app.logger.error(f"Drive upload failed: {str(e)}")
            return None
