from flask import Flask, request, jsonify
from flask_cors import CORS
from Algorithms.TargetFollower import TargetFollower
from Interfaces.DataProcessor import DataProcessor
import numpy as np
import cv2
import base64

app = Flask(__name__)
CORS(app)

data_processor = DataProcessor()

@app.route('/follow-vector', methods=['POST'])
def follow_vector():
    try:
        data = request.json
        detections_info, annotated_image = data_processor.inline_detection(data)

        if not detections_info and annotated_image is None:
            return jsonify({'error': 'No detections found.'}), 400

        # Указываем параметры камеры
        image_height, image_width, _ = annotated_image.shape
        camera_position = np.array([image_width / 2, image_height, 0])

        # todo: add detections_info to the kafka topic

        # Инициализируем TargetFollower и рассчитываем target вектор
        follower = TargetFollower(detections_info, annotated_image, camera_position=camera_position)
        selected_target = follower.select_target('person', nearest=True)
        follow_vector = follower.calculate_follow_vector()

        return jsonify({
            'detections_info': detections_info,
            'follow_vector': follow_vector.tolist()
        })

    except Exception as e:
        return jsonify({'error': str(e)}), 500


if __name__ == '__main__':
    app.run(debug=True)