"""
JaaS Webhook Handler for Recording Storage

This handles webhook events from 8x8 JaaS, particularly RECORDING_UPLOADED events.
When a recording is uploaded, it downloads the recording from the pre-authenticated URL
and stores it on the local server.

Webhook Setup in JaaS Console:
1. Go to https://jaas.8x8.vc/#/webhooks
2. Add your webhook URL: https://yourdomain.com/api/jaas/webhook
3. Select events: RECORDING_STARTED, RECORDING_ENDED, RECORDING_UPLOADED
"""

from flask import Blueprint, request, jsonify
import os
import requests
from datetime import datetime
from threading import Thread

jaas_webhook_bp = Blueprint('jaas_webhook', __name__)

# Directory to store recordings
RECORDINGS_DIR = os.path.join(os.path.dirname(__file__), '..', 'uploads', 'recordings')

# Ensure recordings directory exists
os.makedirs(RECORDINGS_DIR, exist_ok=True)


def download_recording_async(download_url: str, room_name: str, recording_id: str):
    """
    Download recording in background thread
    
    Args:
        download_url: Pre-authenticated URL from JaaS (valid 24h)
        room_name: The Jitsi room name
        recording_id: Unique recording identifier
    """
    try:
        print(f"📥 Downloading recording: {recording_id} for room: {room_name}")
        
        # Create filename with timestamp
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        filename = f"{room_name}_{timestamp}_{recording_id}.mp4"
        filepath = os.path.join(RECORDINGS_DIR, filename)
        
        # Download the file
        response = requests.get(download_url, stream=True, timeout=600)  # 10 min timeout
        response.raise_for_status()
        
        with open(filepath, 'wb') as f:
            for chunk in response.iter_content(chunk_size=8192):
                f.write(chunk)
        
        file_size = os.path.getsize(filepath)
        print(f"✅ Recording saved: {filename} ({file_size / (1024*1024):.2f} MB)")
        
        # Update database with recording URL
        update_live_class_recording(room_name, f"/uploads/recordings/{filename}")
        
    except Exception as e:
        print(f"❌ Failed to download recording: {e}")


def update_live_class_recording(room_name: str, recording_url: str):
    """Update the live_classes table with recording URL"""
    try:
        from config import db
        from models.institute import LiveClass
        
        # Find the live class by room name
        live_class = LiveClass.query.filter_by(jitsi_room_name=room_name).first()
        if live_class:
            live_class.recording_url = recording_url
            live_class.status = 'completed'
            db.session.commit()
            print(f"✅ Updated LiveClass {live_class.id} with recording URL")
        else:
            print(f"⚠️ No LiveClass found for room: {room_name}")
            
    except Exception as e:
        print(f"❌ Failed to update database: {e}")


@jaas_webhook_bp.route('/jaas/webhook', methods=['POST'])
def jaas_webhook():
    """
    Handle JaaS webhook events
    
    Events:
    - RECORDING_STARTED: Recording has started
    - RECORDING_ENDED: Recording has ended (processing)
    - RECORDING_UPLOADED: Recording is ready for download
    
    The RECORDING_UPLOADED payload includes:
    - preAuthenticatedLink: Direct download URL (valid 24 hours)
    - roomName: The meeting room name
    - sessionId: Unique session identifier
    """
    try:
        data = request.get_json()
        
        if not data:
            return jsonify({'status': 'error', 'message': 'No data received'}), 400
        
        event_type = data.get('eventType')
        room_name = data.get('roomName', data.get('data', {}).get('roomName', 'unknown'))
        
        print(f"🎬 JaaS Webhook: {event_type} for room: {room_name}")
        
        if event_type == 'RECORDING_STARTED':
            print(f"🔴 Recording started for room: {room_name}")
            # Optionally update live class status
            
        elif event_type == 'RECORDING_ENDED':
            print(f"⏹️ Recording ended for room: {room_name}")
            # Recording is being processed
            
        elif event_type == 'RECORDING_UPLOADED':
            # Get the pre-authenticated download link
            pre_auth_link = data.get('preAuthenticatedLink')
            recording_id = data.get('sessionId', data.get('id', 'unknown'))
            
            if pre_auth_link:
                print(f"📤 Recording uploaded, starting download...")
                
                # Download in background to not block webhook response
                thread = Thread(
                    target=download_recording_async,
                    args=(pre_auth_link, room_name, recording_id)
                )
                thread.daemon = True
                thread.start()
                
                return jsonify({
                    'status': 'success',
                    'message': 'Recording download initiated',
                    'room_name': room_name
                }), 200
            else:
                print(f"⚠️ No preAuthenticatedLink in payload")
                
        else:
            print(f"📌 Unhandled event type: {event_type}")
        
        return jsonify({'status': 'received', 'event': event_type}), 200
        
    except Exception as e:
        print(f"❌ Webhook error: {e}")
        return jsonify({'status': 'error', 'message': str(e)}), 500


@jaas_webhook_bp.route('/recordings', methods=['GET'])
def list_recordings():
    """List all downloaded recordings"""
    try:
        recordings = []
        for filename in os.listdir(RECORDINGS_DIR):
            if filename.endswith('.mp4'):
                filepath = os.path.join(RECORDINGS_DIR, filename)
                stat = os.stat(filepath)
                recordings.append({
                    'filename': filename,
                    'url': f"/uploads/recordings/{filename}",
                    'size_mb': round(stat.st_size / (1024*1024), 2),
                    'created_at': datetime.fromtimestamp(stat.st_ctime).isoformat()
                })
        
        recordings.sort(key=lambda x: x['created_at'], reverse=True)
        return jsonify({'recordings': recordings}), 200
        
    except Exception as e:
        return jsonify({'message': f'Error: {str(e)}'}), 500
