# Import necessary modules from Flask and Python's os library
from flask import Flask, render_template, request, jsonify
import os

# Create a Flask application instance
app = Flask(__name__)

# Set the directory for uploaded files
app.config['UPLOAD_FOLDER'] = 'uploads'

# Ensure the upload directory exists (create it if not)
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)

# Define the route for the home page.
@app.route('/')
def index():
    # Render the index.html template located in the 'templates' directory.
    return render_template('index.html')

# Define the route for handling POST requests to '/ask'
@app.route('/ask', methods=['POST'])
def ask():
    # Get the 'question' input from the submitted form
    question = request.form.get('question')
    # Get the uploaded file from the submitted form (if any)
    file = request.files.get('file')

    # Start building the response with the user's question
    answer = f"You asked: {question}"
    if file:
        # If a file was uploaded, save it to the upload directory
        filepath = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
        file.save(filepath)
        # Add information about the uploaded file to the response
        answer += f" | Uploaded file: {file.filename}"

    # Send the response back to the client as JSON
    return jsonify({'answer': answer})

# The following block is only needed for local testing and development!
# For deployment with Apache/mod_wsgi, you can remove or comment out this part.
if __name__ == '__main__':
    # Run the Flask development server; accessible from any IP (host='0.0.0.0') on port 5000
    app.run(host='0.0.0.0', port=5000, debug=True)
