import os
from flask import Blueprint, request, jsonify
from config import LABEL_FOLDER
import datetime
from utils import ensure_correct_permissions
save_bp = Blueprint('save', __name__)

@save_bp.route('/save', methods=['POST'])
def save_data():
    arr_points = request.form.get("list")
    image_name = request.form.get("imageName")

    if not arr_points or not image_name:
        return jsonify({"error": "Missing required fields"}), 400

    today_str = datetime.datetime.now().strftime("%Y-%m-%d")

    today_folder = os.path.join(LABEL_FOLDER, today_str)
    os.makedirs(today_folder, exist_ok=True)
    ensure_correct_permissions(today_folder)  

    file_name = os.path.splitext(image_name)[0] 
    file_path = os.path.join(today_folder, f"{file_name}.txt")
    arr_points = arr_points.replace("\r\n", "\n")

    with open(file_path, "w") as file:
        file.write(arr_points)

    return jsonify({"success": True, "list": arr_points, "imageName": image_name})
