# app.py
from flask import Flask, request, jsonify, send_file, after_this_request, Blueprint
from flask_cors import CORS
from App.Utilities_module.FTPUtils import FTPUtils
from pathlib import Path
import mimetypes, tempfile, os, contextlib
from ..services import Ftp_Service


router = Blueprint('FTP', __name__)

@router.get("/getPathFormat/<int:id_format>")
def api_get_path_format(id_format:int):
    path = Ftp_Service.Ftp_Service.get_path_By_id(id_format)
    if path:
        return jsonify({"success": True, "path": path})
    return jsonify({"success": False, "message": "Formato no encontrado"}), 404


@router.get("download/<int:id_format>")
def api_file_download(id_format:int):
    path = Ftp_Service.Ftp_Service.get_path_By_id(id_format)
    if not path:
        return jsonify({"success": False, "message": "Formato no encontrado"}), 404

    suffix = Path(path).suffix or ".bin"
    fd, tmp = tempfile.mkstemp(suffix=suffix)
    os.close(fd)

    res = FTPUtils.download_file(path, tmp)
    if not res.get("success"):
        with contextlib.suppress(Exception):
            os.remove(tmp)
        return jsonify({"success": False, "message": res.get("message")}), 500

    filename = Path(res.get("remote_relative", Path(path).name)).name
    mime = mimetypes.guess_type(filename)[0] or "application/octet-stream"


    @after_this_request
    def _cleanup(resp):
        with contextlib.suppress(Exception):
            os.remove(tmp)
        return resp

    return send_file(tmp, mimetype=mime, as_attachment=True, download_name=filename, max_age=0)


@router.get("/isExist/<int:id_format>")
def api_file_exists(id_format:int):
    path = Ftp_Service.Ftp_Service.get_path_By_id(id_format)
    if not path:
        return jsonify({"success": False, "message": "Falta ?path="}), 400
    exists = FTPUtils.file_exists(path)
    return jsonify({"success": True, "exists": exists, "path": path})

