
from flask import Blueprint, request, jsonify
from audio_io import AudioIO
import os

recording_bp = Blueprint('recording', __name__)

@recording_bp.route('/record/start', methods=['POST'])
def start_recording():
    recorder = AudioIO()
    print('HTTP: Starting audio recording')
    recorder.start_recording()
    return jsonify({'status': 'recording started'})

@recording_bp.route('/record/stop', methods=['POST'])
def stop_recording():
    recorder = AudioIO()
    # print('HTTP: Stopping audio recording')
    recorder.stop_recording()
    return jsonify({'status': 'recording stopped'})

@recording_bp.route('/record/save', methods=['POST'])
def save_recording():
    recorder = AudioIO()
    # print('HTTP: Saving audio recording')
    saved_file = recorder.save_last_n_seconds()
    return jsonify({'status': 'recording saved', 'file': saved_file})


@recording_bp.route('/record/status', methods=['GET'])
def recording_status():
    recorder = AudioIO()
    # print('HTTP: Checking recording status')
    status = 'recording' if recorder.is_recording() else 'stopped'
    return jsonify({'status': status})

@recording_bp.route('/record/delete', methods=['POST'])
def recording_delete():
    filename = request.json.get('filename')
    try:
        os.remove(filename)
        return jsonify({'status': 'success'})
    except Exception as e:        
        return jsonify({'status': 'error', 'message': str(e)}), 400
    
@recording_bp.route('/playback/start', methods=['POST'])
def playback_start():
    print(f"Playing clip")
    # print('HTTP: Starting audio playback')
    clip = request.json
    try:
        io = AudioIO()
        io.play_clip(clip)
        # os.remove(filename)
        return jsonify({'status': 'success'})
    except Exception as e:        
        return jsonify({'status': 'error', 'message': str(e)}), 400