from flask import current_app
from flask_restx import Namespace, Resource, reqparse

from app.models.file import File

from app.tasks.face_tasks import process_faces


face_namespace = Namespace('faces', description='Face Detection and Tracking ML operations')

face_parser = reqparse.RequestParser()
face_parser.add_argument('file_id', type=int, required=True, help='ID of the file to process')

@face_namespace.route('/')
class FaceDetectionTracking(Resource):
    @face_namespace.expect(face_parser)
    def post(self):
        args = face_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_video_extensions = current_app.config.get('SUPPORTED_VIDEO_EXTENSIONS', [])

            if file.extension in supported_video_extensions:
                # Run Celery task to perform face detection and tracking
                task = process_faces.delay(file.filepath)

                return {
                    'message': 'Face detection task started',
                    'task': {
                        'id': task.id,
                        'status': task.status,
                    }
                }, 202  # Accepted

            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

@face_namespace.route('/results/<task_id>')
class FaceDetectionResults(Resource):
    def get(self, task_id):
        try:
            task = process_faces.AsyncResult(task_id)

            if task.state == 'PENDING':
                return {'message': 'Task is still pending.'}, 202

            elif task.state == 'STARTED':
                return {'message': 'Task is in progress.'}, 202

            elif task.state == 'SUCCESS':
                face_data = task.get()
                return {'face_data': face_data}, 200

            elif task.state == 'FAILURE':
                return {'message': 'Task failed.'}, 500

            else:
                return {'message': 'Invalid task state.'}, 400

        except Exception as e:
            print(f"Error retrieving face detection results: {e}")
            return {'message': 'An error occurred while retrieving face detection results.'}, 500