#from flask import Flask, request, jsonify, session, send_from_directory
from flask import Flask, request, jsonify, session, send_from_directory, render_template, url_for
from flask_cors import CORS
from qa_system import get_next_part, get_recommendation, get_answer
from openai import OpenAI
import logging

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

client = OpenAI(api_key='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')  # Import OpenAI library

#app = Flask(__name__, static_folder='media')
app = Flask(__name__, static_folder='static', template_folder='templates')
CORS(app)
app.secret_key = 'super_secret_key'

# OpenAI API Key setup

# Maximum phase (end of the process)
MAX_PHASE = 12
logging.info(f"MAX PHASE setting: {MAX_PHASE}")

# Serve the index.html file through render_template to process Jinja2 expressions
@app.route('/')
def index():
    return render_template('index.html')  # Render the HTML template


# Serve static files (if you have CSS or JS)
@app.route('/static/<path:path>')
def static_files(path):
    return send_from_directory('static', path)

# Serve the index.html file
#@app.route('/')
#def index():
#    return send_from_directory('/var/www/html/test1/', 'index.html')

# Serve static files (if you have CSS or JS)
#@app.route('/test1/<path:path>')
#def static_files(path):
#    return send_from_directory('/var/www/html/test1/', path)

import re

def parse_instructions(phase_text):
    # Split into segments alternating between text and <sound:...> markers
    segments = re.split(r'(<sound:[\w-]+>)', phase_text)

    #print("Segments after split:", segments)

    # Prepare structured segments and unique sound files list
    sanitized_segments = []
    sound_files = set()

    for segment in segments:
        if "<sound:" in segment:  # Check if segment contains a sound marker
            # Extract the sound filename from the marker
            sound_marker = re.search(r'<sound:([\w-]+)>', segment)
            if sound_marker:
                filename = sound_marker.group(1)
                sanitized_segments.append({"type": "sound", "value": filename})
                sound_files.add(filename)  # Collect unique filenames
        else:
            # Add non-empty text segments only
            text_content = segment.strip()
            if text_content:  # Only append if not empty
                sanitized_segments.append({"type": "text", "value": text_content})

    # Convert sound_files set to list before returning
    sound_files_list = list(sound_files)
    return sanitized_segments, sound_files_list

# Route to reset the phase counter
@app.route('/reset-phase', methods=['POST'])
def reset_phase():
    session.clear()  # Clear the entire session
    session['phase'] = 0  # Set phase to 0 when the process starts (before phase 1)
    return jsonify({"message": "Phase reset to 0"}), 200



@app.route('/next-phase', methods=['POST'])
def next_phase():
    data = request.get_json()
    choice = data.get('choice', "A")  # Default to choice A (continue)
    current_phase = session.get('phase', 0)  # Start at phase 0 before moving to phase 1
    logging.info(f"current phase when entering function next_phase: {current_phase}")
    # Logic for starting the process
    if current_phase == 0:  # Initial phase (start of the process)
        current_phase = 1  # Move to phase 1 for the first set of instructions

    # Ensure this line is correctly aligned with `if` and not nested incorrectly
        logging.info(f"MAX PHASE setting: {MAX_PHASE}")
    elif current_phase == MAX_PHASE:
        if choice == 'A':  # Go to the end
            current_phase = 13
        elif choice == 'B':  # Go back to phase 11
            pass

    else:
        if choice == 'A':  # Continue to the next phase
            current_phase += 1
            logging.info(f"current phase after increment: {current_phase}")
        elif choice == 'B':  # Repeat the current phase
            pass  # Keep the current phase unchanged

    # Save the updated phase in the session
    session['phase'] = current_phase
    # Get the content for the current phase
    phase_text, questions = get_next_part(current_phase)

    # Parse instructions and sound markers
    segmented_instructions, sound_files = parse_instructions(phase_text)

    #print(f"Instructions: {segmented_instructions}")
    logging.info(f"segmented instructions: {segmented_instructions}")
    #print(f"Sound files: {sound_files}")
    logging.info(f"sound files: {sound_files}")

    # Return the content along with the current phase and sound files as JSON
    return jsonify({
        'segmentedInstructions': segmented_instructions,
        'questions': questions,
        'phase': current_phase,  # Ensure phase is returned here
        'soundFiles': sound_files,  # List of sound files for the current phase
        'is_last_phase': current_phase == 13  # Added to indicate the end
    })


# Function to query ChatGPT for feedback-based recommendations
def get_chatgpt_recommendation(feedback):
    try:
        # Correct usage of the ChatGPT API for conversation style completion
        response = client.chat.completions.create(model="gpt-4",  # Make sure you are using the correct model name
        messages=[
            # {"role": "system", "content": "You are a trauma assistant guiding a patient through mental exercises."},
            # {"role": "user", "content": f"The user provided the following feedback: '{feedback}'. Based on this feedback, should the user proceed to the next phase or repeat >
            {"role": "system", "content": "You are a trauma assistant guiding a patient through mental exercises. Provide recommendations by directly addressing the user in the>
            {"role": "user", "content": f"I just completed an exercise and my feedback is: '{feedback}'. Based on this feedback, should I proceed to the next phase or repeat th>
        ])
        # Extract and return the model's response
        return response.choices[0].message.content
    except Exception as e:
        #print(f"Error in OpenAI API: {e}")  # Log the exact error message
        logging.info(f"openAI error: {e}")
        return "Error in generating a recommendation."





# Route to handle feedback submission and return a ChatGPT-generated recommendation
@app.route('/feedback', methods=['POST'])
def feedback():
    data = request.get_json()
    feedback_text = data.get('feedback', '')

    # Get recommendation from ChatGPT based on feedback
    recommendation = get_chatgpt_recommendation(feedback_text)

    # Send the recommendation back to the frontend
    return jsonify({"recommendation": recommendation})

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)

