from flask import Flask, request, send_file, jsonify,render_template
import requests
from io import BytesIO

app = Flask(__name__)

@app.route('/', methods=['GET'])
def index():
    return render_template('appy.html')

@app.route('/list_faces', methods=['POST'])
def list_faces():
    url = request.json.get('url')
    try:
        response = requests.get(url)
        return jsonify(response.json())
    except Exception as e:
        return jsonify({'error': str(e)})

@app.route('/get_image', methods=['POST'])
def get_image():
    base_url = request.json.get('base_url')
    bucket = request.json.get('bucket')
    image_path = request.json.get('image_path')
    
    try:
        # Construir a URL completa
        full_url = f"{base_url}/{bucket}/{image_path}"
        
        # Fazer a requisição GET para obter a imagem
        response = requests.get(full_url, stream=True)
        response.raise_for_status()  # Lança exceção se o status for 4xx ou 5xx
        
        # Retornar a imagem como um arquivo para o front-end
        return send_file(
            BytesIO(response.content), 
            mimetype='image/jpeg',  # Ajuste o mimetype conforme o formato da imagem (jpeg, png, etc.)
            download_name='image.jpg'  # Nome sugerido do arquivo, opcional
        )
    except requests.exceptions.RequestException as e:
        return jsonify({'error': str(e)}), 400
@app.route('/update_name', methods=['POST'])
def update_name():
    url = request.json.get('url')
    userID = request.json.get('userID')
    new_name = request.json.get('new_name')
    
    try:
        
        full_url = f"{url}/{userID}/{new_name}"
        
        response = requests.post(full_url)
        response.raise_for_status() 
    
        return jsonify(response.json())
    except requests.exceptions.RequestException as e:
        return jsonify({'error': str(e)}), 400
if __name__ == '__main__':
    app.run(debug=True)
