import os
from click import File
from flask import Flask, request, jsonify
from utility import toYaml, create_crd, deploy
import uuid
from datetime import datetime
app = Flask(__name__)

# route to receive the requirements
@app.route('/api/upload_json', methods=['POST'])
def upload_json():

    date = datetime.today().strftime('%Y-%m-%d')
    random_string = str(uuid.uuid4())
    try:

        if 'file' not in request.files:
            return jsonify({"message": "No file received"}), 400

        file = request.files['file']

        if file.filename == '':
            return jsonify({"message": "No filename is specified "}), 400
        #creates the directory where the files will be stored
        outputDir = "outputs_"+date+ "_"+random_string
        if not os.path.exists(outputDir):
            os.makedirs(outputDir)
        output_path = os.path.join(outputDir, file.filename)
        file.save(output_path)
        create_crd(outputDir)
        setupResult = toYaml(outputDir)
        if setupResult:
            return jsonify({"status": "error", "message": f"Requirement not found: {', '.join(setupResult)}"}), 400
        else:
            return jsonify({"status": "success", "message": "Setup successful"}), 200


    except Exception as e:
        return jsonify({"message": str(e)}), 500

# route to start the operator
@app.route('/api/deploy', methods=['GET'])
def run_operator():
    try:
        deploy()
        return jsonify({"message": "Deployment successful"}), 200

    except Exception as e:
        return jsonify({"message": str(e)}), 500


if __name__ == '__main__':
    #app.run(host="0.0.0.0", port=28900, debug=True) # accessible on all network interfaces
    app.run(host="127.0.0.1", port=28900, debug=True) # accessible on the loopback interface (127.0.0.1 or localhost)
