# -*- coding: utf-8 -*-
# Copyright 2026 Nexa Systems Inc.
# License OPL-1 (Odoo Proprietary License v1.0)

import logging

import requests as py_requests

from odoo import http
from odoo.http import request, Response

_logger = logging.getLogger(__name__)


class RcRecordingController(http.Controller):

    @http.route('/ringcentral/recording/<int:call_id>', type='http', auth='user')
    def stream_recording(self, call_id, **kw):
        """Proxy a call recording from RingCentral with authentication."""
        call = request.env['rc.call.history'].browse(call_id)
        if not call.exists() or not call.recording_content_uri:
            return Response('Recording not found', status=404)

        config = request.env['rc.config']._get_active_config()
        if not config:
            return Response('RingCentral not configured', status=503)

        try:
            config._ensure_token()
            resp = py_requests.get(
                call.recording_content_uri,
                headers={'Authorization': f'Bearer {config.access_token}'},
                stream=True,
                timeout=30,
                verify=config.ssl_verify,
                proxies=config._get_proxies(),
            )
            resp.raise_for_status()

            content_type = resp.headers.get('Content-Type', 'audio/mpeg')
            return Response(
                resp.iter_content(chunk_size=4096),
                content_type=content_type,
                headers={
                    'Content-Disposition': f'inline; filename="recording_{call_id}.mp3"',
                },
            )
        except Exception:
            _logger.exception("Error streaming recording for call %s", call_id)
            return Response('Error streaming recording', status=500)
