from flask import Flask, request, render_template, redirect, url_for, flash
import os
import openai
from werkzeug.utils import secure_filename

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads'
app.secret_key = 'your-secret-key'  # replace with a strong secret in production

# Load OpenAI API key from environment variable
openai.api_key = os.getenv("OPENAI_API_KEY")

# Ensure upload folder exists
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)


@app.route('/dashboard')
def dashboard():
    """
    List uploaded files in the dashboard. Only displays filenames, not content.
    """
    files = os.listdir(app.config['UPLOAD_FOLDER'])
    return render_template('dashboard.html', files=files)


@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
    """
    Handle PDF or Word file uploads via a simple web form.
    """
    if request.method == 'POST':
        file = request.files.get('file')
        if file:
            filename = secure_filename(file.filename)
            filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
            file.save(filepath)
            flash('File uploaded successfully', 'success')
            return redirect(url_for('dashboard'))
    return render_template('upload.html')


@app.route('/webhook', methods=['POST'])
def webhook():
    """
    A basic webhook endpoint that reads incoming messages from WhatsApp (or any chat
    provider) and uses OpenAI's GPT engine to generate a response. The prompt
    enforces a bilingual assistant persona that can respond in Arabic and English
    depending on user input. If the API key is not set or an error occurs, a
    generic apology is returned.
    """
    data = request.json or request.form
    incoming_message = data.get('Body') or data.get('message') or ''
    if incoming_message:
        # Compose a bilingual prompt instructing the assistant to answer politely.
        prompt = (
            "You are a professional bilingual (Arabic and English) virtual assistant for "
            "Damak Business Management. You should respond to users using the same "
            "language they use. Keep responses short, professional, and helpful.\n\n"
            f"User: {incoming_message}\n"
            "Assistant:"
        )
        try:
            response = openai.Completion.create(
                engine="text-davinci-003",
                prompt=prompt,
                max_tokens=100,
                temperature=0.5,
                n=1,
                stop=None
            )
            reply = response.choices[0].text.strip()
        except Exception:
            reply = "Sorry, an error occurred. Please try again later."
    else:
        reply = "Hello! How may I help you?"
    return reply


if __name__ == '__main__':
    # For local testing; in production remove debug=True
    app.run(host='0.0.0.0', port=5000, debug=True)