
import os
from flask import current_app
from flask_restx import Namespace, Resource, reqparse 

from app.models.file import File
from app.utils.file_handler import FileHandler
from app.core.extensions import db

speech_namespace = Namespace('stt', description='Speech To Text ML operations')

# Define the expected input parameters
parser = reqparse.RequestParser()
parser.add_argument('file_id', type=int, required=True, help='ID of the file to process')

@speech_namespace.route('/')
class SpeechToText(Resource):
    @speech_namespace.expect(parser)
    def post(self):
        args = parser.parse_args()
        file_id = args['file_id']

        # Get the file from the database
        file = File.query.get(file_id)
        if not file:
            return {'message': 'File not found'}, 404
        try:
            supported_audio_extensions = current_app.config.get('SUPPORTED_AUDIO_EXTENSIONS', [])
            supported_video_extensions = current_app.config.get('SUPPORTED_VIDEO_EXTENSIONS', [])   
            # Check if the file is an audio file with WAV extension
            if file.extension == 'wav':
                # # Run Celery task to process the audio
                # process_audio.delay(audio_file)
                return {'message': 'Text extracted successfully'}, 200
            elif file.extension in supported_audio_extensions:
                # Convert non-WAV audio to WAV format
                audio_file_path = FileHandler.convert_to_wav(
                    file.filepath, 
                    f"{current_app.config.get('UPLOAD_DIR', 'data')}/wavs/{os.path.splitext(os.path.basename(file.filepath))[0]}.wav" 
                ) 
                # Run Celery task to process the audio
                # process_audio.delay(audio_file)
                return {'message': 'Audio processing task started'}, 200
            elif file.extension in supported_video_extensions:
                # Convert non-WAV audio to WAV format
                audio_file_path = FileHandler.convert_to_wav(
                    file.filepath, 
                    f"{current_app.config.get('UPLOAD_DIR', 'data')}/wavs/{os.path.splitext(os.path.basename(file.filepath))[0]}.wav" 
                ) 
                # Run Celery task to process the audio
                # process_audio.delay(audio_file_path)
                return {
                    'data': audio_file_path,
                    'message': 'Audio processing task started'
                    }, 200
            else:
                return {'message': 'Unsupported file format'}, 400    
        except Exception as e:
            print(f"Error processing file: {e}")
            return {'message': 'An error occurred while processing the file.'}, 500