from flask import Flask, render_template, request, redirect, url_for, session
from nltk.sentiment.vader import SentimentIntensityAnalyzer
import mysql.connector
import bcrypt
import datetime
import json
import smtplib
from email.message import EmailMessage
import secrets
import string


mysql = mysql.connector.connect(
    host='sql12.freemysqlhosting.net',
    user='sql12673861',
    password='gURFKWEA9G',
    database='sql12673861',
    port=3306,
)


app = Flask(__name__)
app.static_folder = 'static'
app.static_url_path = '/static'

app.secret_key = "smilecheck-abhi-2023"


@app.route('/')
def index():
    return render_template("index.html")


@app.route('/home', methods=["GET", "POST"])
def home():
    if request.method == 'GET':
        if 'email' in session:
            app.config['MYSQL_DB'] = 'sql12673861'
            curh = mysql.cursor()
            if session['usertype'] == 0:
                curh.execute("SELECT `assessid`, `name` FROM `h_assessments`")
                typedata = curh.fetchall()

                converted_tuple = tuple({'assessid': item[0], 'name': item[1]} for item in typedata)

                curh.execute("SELECT `id`, `type` FROM `h_custom` WHERE id=%s", (session['id'],))
                given = curh.fetchall()
                isdone = []
                for give in given:
                    isdone.append(give[1])

                curh.execute("SELECT `name`, `happy`, `datetime` FROM `h_custom`, `h_assessments` WHERE custom.type = assessments.assessId AND id=%s", (session['id'],))
                previous = curh.fetchall()

                preprocessed_data = []
                for index, row in enumerate(previous):
                    preprocessed_data.append({
                        'index': index + 1,
                        'name': row[0],
                        'happy': row[1],
                        'datetime': row[2]
                    })

                return render_template("home.html", typedata=converted_tuple, given=isdone, previous=preprocessed_data )

            elif session['usertype'] == 1:
                return redirect(url_for('admin'))
            mysql.commit()
            curh.close()
        else:
            return redirect(url_for('login'))

    if request.method == 'POST':
        if 'email' in session:
            app.config['MYSQL_DB'] = 'sql12673861'

            curh = mysql.cursor()

            if 'fname' in request.form:
                fname = request.form['fname']
                femail = request.form['femail']
                feedback = request.form['feedback']
                curh.execute("INSERT INTO `h_feedbacks`(`name`, `email`, `feedback`) VALUES (%s, %s, %s)", (fname, femail, feedback,))
                mysql.commit()
                curh.close()
                session['feed'] = 1
                return redirect(url_for('home'))


            session['type'] = request.form['type']

            curh.execute("SELECT `id`, `type` FROM `h_custom` WHERE id=%s AND type=%s", (session['id'], session['type'],))
            given = curh.fetchone()
            mysql.commit()
            curh.close()

            if given == None:
                return redirect(url_for('form'))
            else:
                return redirect(url_for('result'))

        else:
            return redirect(url_for('login'))

    return render_template("home.html")


@app.route('/register', methods=["GET", "POST"])
def register():
    if request.method == 'GET':
        return render_template("register.html", error_code=999, message_code=999)

    if request.method == 'POST':
        database = request.form['database']
        if database == 'database1':
            app.config['MYSQL_DB'] = 'sql12673861'
            session['database'] = app.config['MYSQL_DB']
        elif database == 'database2':
            app.config['MYSQL_DB'] = 'sql12673861'
            session['database'] = app.config['MYSQL_DB']

        name = request.form['name']
        email = request.form['email']
        cur = mysql.cursor()
        cur.execute("SELECT * FROM `h_users` WHERE email = %s", (email,))
        user = cur.fetchone()
        mysql.commit()
        cur.close()

        if user:
            error = 'Email address already in use. Please use a different email address.'
            return render_template('register.html', error=error, error_code=550, message_code=569)
        else:
            session['name'] = name
            session['email'] = email
            usertype = 'student'
            session['pretype'] = usertype
            password = request.form['password'].encode('utf-8')
            hash_password = bcrypt.hashpw(password, bcrypt.gensalt())
            session['hash'] = hash_password

            msg = EmailMessage()

            alphabet = string.ascii_letters + string.digits
            otp = 'smilecheck-user-'+''.join(secrets.choice(alphabet) for i in range(30))
            session['otp'] = otp

            msg["Subject"] = "SmileCheck Verification"
            msg["From"] = "smilecheck100@gmail.com"
            msg["To"] = email
            link = f"https://abhicodes-smilecheck.hf.space/verify/{otp}"

            html_content = render_template('email.html', name=name, link=link)
            msg.set_content(html_content, subtype='html')

            with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
                smtp.login('smilecheck23@gmail.com', 'dczcfrdkthwcfoqu')
                smtp.send_message(msg)

            return render_template('register.html', message='An Verification Email has been sent to your email address.', message_code=560, error_code=568)


@app.route('/verify/<otp>')
def verify(otp):
    if str(session['otp']) == otp:
        app.config['MYSQL_DB'] = 'sql12673861'

        cur = mysql.cursor()
        cur.execute("INSERT INTO `h_users` (name, email, password) VALUES (%s,%s,%s)", (session['name'], session['email'], session['hash'],))

        if session['pretype'] == 'student':
            cur.execute("UPDATE `h_users` SET `usertype` = %s WHERE `email`=%s", (0, session['email'],))
            session['usertype'] = 0
        elif session['pretype'] == 'admin':
            cur.execute("UPDATE `h_users` SET `usertype` = %s WHERE `email`=%s", (1, session['email'],))
            session['usertype'] = 1

        mysql.commit()
        cur.close()

        session.clear()

        redi = 'login'
        return render_template('verify.html', message=111, redirect_url=redi)

    else:
        redi = 'register'
        return render_template('verify.html', message=999, redirect_url=redi)


@app.route('/login', methods=["GET", "POST"])
def login():
    if request.method == 'GET':
        return render_template("login.html", error_code=999)

    if request.method == 'POST':
        now = datetime.datetime.now()
        database = request.form['database']
        if database == 'database1':
            app.config['MYSQL_DB'] = 'sql12673861'
        elif database == 'database2':
            app.config['MYSQL_DB'] = 'sql12673861'

        email = request.form['email']
        password = request.form['password'].encode('utf-8')

        curl = mysql.cursor()
        curl.execute("SELECT * FROM `h_users` WHERE email=%s", (email,))
        user = curl.fetchone()

        if user != None:
            if bcrypt.hashpw(password, user[4].encode('utf-8')) == user[4].encode('utf-8'):

                session['id'] = user[0]
                session['name'] = user[2]
                session['email'] = user[3]
                session['database'] = 'sql12673861'

                print(session)

                curl.execute("INSERT INTO `h_session` (id, email, action, actionC, datetime) VALUES (%s, %s, %s, %s, %s)", (session['id'], session['email'], 'Logged In - Session Started', 1, now,))
                mysql.commit()
                curl.close()

                if user[1] == 0:
                    session['usertype'] = 0
                    return redirect(url_for('home'))
                elif user[1] == 1:
                    session['usertype'] = 1
                    return redirect(url_for('admin'))

            else:
                return render_template("login.html", error="Error: Password or Email are incorrect.", error_code=451)

        else:
            return render_template("login.html", error="Error: User not found. Please register.", error_code=452)

        mysql.commit()
        curl.close()
    else:
        return render_template("login.html")


@app.route('/forgot', methods=["GET", "POST"])
def forgot():
    if request.method == 'GET':
        return render_template("forgot.html")

    if request.method == 'POST':
        app.config['MYSQL_DB'] = 'sql12673861'

        email = request.form['email']
        session['email'] = email

        curl = mysql.cursor()
        curl.execute("SELECT * FROM `h_users` WHERE email=%s", (email,))
        user = curl.fetchone()

        mysql.commit()
        curl.close()

        if user != None:
            msg = EmailMessage()

            name= user[2]

            alphabet = string.ascii_letters + string.digits
            otp = 'smilecheck-pass-' + ''.join(secrets.choice(alphabet) for i in range(30))
            session['otp'] = otp
            msg["Subject"] = "SmileCheck Verification"
            msg["From"] = "smilecheck100@gmail.com"
            msg["To"] = email
            link = f"https://abhicodes-smilecheck.hf.space/password/{otp}"

            html_content = render_template('pass.html', name=name, link=link)
            msg.set_content(html_content, subtype='html')

            with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
                smtp.login('smilecheck23@gmail.com', 'dczcfrdkthwcfoqu')
                smtp.send_message(msg)

            return render_template('register.html', message='An Verification Email has been sent to your email address.', message_code=560, error_code=568)

        else:
            return render_template("forgot.html", mess="No such User Found.")


@app.route('/password/<otp>', methods=["GET", "POST"])
def password(otp):
    if str(session['otp']) == otp:
        redi = 'change'
        return render_template('password.html', message=111, redirect_url=redi)
    else:
        redi = 'login'
        return render_template('password.html', message=999, redirect_url=redi)


@app.route('/change', methods=["GET", "POST"])
def change():
    if request.method == 'GET':
        return render_template("change.html")

    if request.method == 'POST':
        app.config['MYSQL_DB'] = 'sql12673861'

        password = request.form['password'].encode('utf-8')
        hash_password = bcrypt.hashpw(password, bcrypt.gensalt())

        curl = mysql.cursor()
        curl.execute("UPDATE `h_users` SET `password`=%s WHERE email=%s", (hash_password, session['email'],))

        mysql.commit()
        curl.close()

        session.clear()

        return redirect(url_for('login'))


@app.route('/admin', methods=["GET", "POST"])
def admin():
    if 'email' in session:
        if session['usertype'] == 0:
            return redirect(url_for('home'))
    else:
        return redirect(url_for('login'))

    if request.method == 'GET':
        if 'email' in session:
            app.config['MYSQL_DB'] = 'sql12673861'

            cura = mysql.cursor()

            cura.execute("SELECT `assessid`, `name` FROM `h_assessments`")
            typedata = cura.fetchall()

            typedata_tuple = tuple({'assessid': item[0], 'name': item[1]} for item in typedata)

            cura.execute("SELECT `id`, `type` FROM `h_custom`")
            given = cura.fetchall()

            given_tuple = tuple({'id': item[0], 'type': item[1]} for item in given)

            isdone = []
            for give in given:
                isdone.append(give[1])

            cura.execute("SELECT `id`, `name`, `email`, `isdone` FROM `h_users` WHERE `usertype` = 0")
            res = cura.fetchall()

            res_tuple = tuple({'id': item[0], 'name': item[1], 'email': item[2], 'isdone': item[3]} for item in res)

            cura.execute("SELECT `assessId`, `name`, `description`, `Questions`, `average` FROM `h_assessments`")
            que = cura.fetchall()

            que_tuple = tuple({'assessId': item[0], 'name': item[1], 'description': item[2], 'Questions': item[3], 'average': item[4]} for item in que)

            cura.execute("SELECT `id`, `type`, `name` FROM `h_custom`, `h_assessments` WHERE h_custom.type = h_assessments.assessId")
            abc = cura.fetchall()

            abc_tuple = tuple({'id': item[0], 'type': item[1], 'name': item[2]} for item in abc)

            ahi = 0.0
            for assess in que:
                if assess[0] == 101:
                    ahi = assess[4]

            ts = len(res)
            tas = len(isdone)

            cura.execute("SELECT `name`, `email`, `feedback` FROM `h_feedbacks`")
            feeds = cura.fetchall()

            feeds_tuple = tuple({'name': item[0], 'email': item[1], 'feedback': item[2]} for item in feeds)

            mysql.commit()
            cura.close()

            return render_template("admin.html", typedata=typedata_tuple, given=given_tuple, result=res_tuple, assess=que_tuple, abc=abc_tuple, ts=ts, ahi=ahi, tas=tas, feeds= feeds_tuple)

    if request.method == "POST":
        app.config['MYSQL_DB'] = 'sql12673861'

        if 'resid' in request.form:
            resid = request.form.get('resid')
            types = request.form.get('type')

            session['id'] = resid
            session['type'] = types

            return redirect(url_for('result'))

        elif 'delete' in request.form:
            cura = mysql.cursor()
            deleteId = request.form['delete']
            cura.execute("DELETE FROM `h_assessments` WHERE `assessId`= %s", (deleteId,))
            mysql.commit()
            cura.close()
            return redirect(url_for('admin'))

    return render_template('admin.html')


@app.route('/form', methods=["GET", "POST"])
def form():
    if 'email' not in session:
        return redirect(url_for('login'))

    if request.method == "GET":
        app.config['MYSQL_DB'] = 'sql12673861'
        typeid = session['type']
        curf = mysql.cursor()
        curf.execute("SELECT `name`, `description`, `Questions`, `types` FROM `h_assessments` WHERE assessid = %s", (typeid,))
        questions = curf.fetchone()

        mysql.commit()
        curf.close()

        return render_template("form.html", questions=questions)

    if request.method == "POST":
        app.config['MYSQL_DB'] = 'sql12673861'

        data = request.form.to_dict()

        length = len(request.form)
        inp = []
        for i in range(0, length):
            inp.append(data['inp' + str(i + 1) + ''])

        sid_obj = SentimentIntensityAnalyzer()

        compound = []
        for i in range(0, length):
            compound.append(sid_obj.polarity_scores(data['inp' + str(i + 1) + ''])['compound'] * 100)

        now = datetime.datetime.now()
        cur = mysql.cursor()

        query = "INSERT INTO `h_custom` (`Id`, `type`, `response`, `result`, `datetime`) VALUES (%s, %s, %s, %s, %s)"
        cur.execute(query, (session['id'], session['type'], json.dumps(inp), json.dumps(compound), now,))

        query = "UPDATE `h_users` SET `isdone`=%s WHERE `id`=%s"
        cur.execute(query, (1, session['id'],))

        cur.execute("SELECT * FROM `h_custom` WHERE id=%s AND type=%s", (session['id'], session['type'],))
        res = cur.fetchone()

        cur.execute("SELECT qval FROM `h_assessments` WHERE assessId=%s", (session['type'],))
        qval = cur.fetchone()

        multi = eval(qval[0])
        happy = eval(res[4])
        for j in range(len(happy)):
            happy[j] = happy[j] * multi[j]

        min_value = min(compound)
        max_value = max(compound)
        scaled_values = [(value - min_value) / (max_value - min_value) * 5 for value in compound]

        happy_index = round(sum(scaled_values) / len(scaled_values), 2)

        query = "UPDATE `h_custom` SET `happy`=%s WHERE `id`=%s AND `type`=%s"
        cur.execute(query, (happy_index, session['id'], session['type'],))

        cur.execute("SELECT `happy` FROM `h_custom` WHERE type=%s", (session['type'],))
        avg_dict = cur.fetchall()

        avg_list = [d[0] for d in avg_dict if isinstance(d[0], float)] + [item for d in avg_dict if isinstance(d[0], (list, tuple)) for item in d[0]]

        avg_score = round(sum(avg_list)/len(avg_list), 2)

        query = "UPDATE `h_assessments` SET `average`=%s WHERE `assessId`=%s"
        cur.execute(query, (avg_score, session['type'],))

        mysql.commit()
        cur.close()

        '''Re-render template...'''

        return redirect(url_for('result'))

    return redirect(url_for('result'))


@app.route('/custom', methods=["GET", "POST"])
def custom():
    if 'email' not in session:
        return redirect(url_for('login'))

    if request.method == "GET":
        if session['usertype'] == 0:
            return redirect(url_for('home'))

        return render_template('custom.html')

    if request.method == "POST":
        app.config['MYSQL_DB'] = 'sql12673861'

        data = request.form.to_dict()

        length = len(request.form)
        inp = []
        for i in range(0, int((length - 3)/2)):
            inp.append(data['inpt' + str(i + 1) + ''])

        sid_obj = SentimentIntensityAnalyzer()

        compound = []
        for i in range(0, int((length - 3)/2)):
            compound.append(sid_obj.polarity_scores(data['inpt' + str(i + 1) + ''])['compound'] * 100)

        types = []
        for i in range(0, int((length - 3) / 2)):
            types.append(int(data['select' + str(i + 1) + '']))

        for i in range(len(compound)):
            if compound[i] < 0:
                compound[i] = -1
            elif compound[i] >= 0:
                compound[i] = 1

        name = request.form['name']
        describ = request.form['describ']

        '''SQL Queries for data storing in database...'''

        now = datetime.datetime.now()
        cur = mysql.cursor()

        query = "INSERT INTO `h_assessments` (`name`, `description`, `Questions`, `types`, `qval`) VALUES (%s, %s, %s, %s, %s)"
        cur.execute(query, (name, describ, json.dumps(inp), json.dumps(types), json.dumps(compound),))

        mysql.commit()
        cur.close()

        return redirect(url_for('admin'))

    return render_template("custom.html")


@app.route('/result')
def result():
    if 'email' not in session:
        return redirect(url_for('home'))

    app.config['MYSQL_DB'] = 'sql12673861'
    curr = mysql.cursor()

    curr.execute("SELECT * FROM `h_custom` WHERE id=%s AND type=%s", (session['id'], session['type'],))
    res = curr.fetchone()

    curr.execute("SELECT `result` FROM `h_custom` WHERE type=%s", (session['type'],))
    avg = curr.fetchall()

    dynamic = [list(eval(d[0])) for d in avg]

    dyna = []
    i = 0
    for i in range(len(dynamic[i])):
        temp2 = 0
        for j in range(len(dynamic)):
            temp2 = temp2 + dynamic[j][i]
        dyna.append(temp2 / len(dynamic))

    ques = []
    for i in range(1, len(dyna) + 1):
        ques.append("Question " + str(i) + "")

    curr.execute("SELECT * FROM `h_assessments` WHERE assessid = %s", (session['type'],))
    questions = curr.fetchone()

    curr.execute("SELECT * FROM `h_suggestions`")
    suggests = curr.fetchall()
    response = []
    mapper = eval(questions[4])
    score = eval(res[4])

    score_dict = {}
    for i in range(len(mapper)):
        if mapper[i] not in score_dict:
            score_dict[mapper[i]] = []
        score_dict[mapper[i]].append(score[i])

    result_dict = {}

    for key, value in score_dict.items():
        temp_score = sum(value) / len(value)
        avg_score = round(((temp_score + 100) / 200) * (90 - 10) + 10, 2)
        if key == 1101:
            if avg_score >= 66:
                result_dict[key] = {"average_score": avg_score, "name": "Psychological well being",
                                    "description": "Refers to an individual`s mental state and overall happiness, including feelings of fulfillment, purpose, and contentment.",
                                    "suggestions_text": [list(eval(d[3])) for d in suggests if d[0] == 1101]}
            elif avg_score >= 30:
                result_dict[key] = {"average_score": avg_score, "name": "Psychological well being",
                                    "description": "Refers to an individual`s mental state and overall happiness, including feelings of fulfillment, purpose, and contentment.",
                                    "suggestions_text": [list(eval(d[2])) for d in suggests if d[0] == 1101]}
            elif avg_score < 30:
                result_dict[key] = {"average_score": avg_score, "name": "Psychological well being",
                                    "description": "Refers to an individual`s mental state and overall happiness, including feelings of fulfillment, purpose, and contentment.",
                                    "suggestions_text": [list(eval(d[1])) for d in suggests if d[0] == 1101]}

        elif key == 1102:
            if avg_score >= 66:
                result_dict[key] = {"average_score": avg_score, "name": "Health aspects",
                                    "description": "Refers to an individual`s physical health, including factors such as nutrition, exercise, and access to medical care.",
                                    "suggestions_text": [list(eval(d[3])) for d in suggests if d[0] == 1102]}
            elif avg_score >= 30:
                result_dict[key] = {"average_score": avg_score, "name": "Health aspects",
                                    "description": "Refers to an individual`s physical health, including factors such as nutrition, exercise, and access to medical care.",
                                    "suggestions_text": [list(eval(d[2])) for d in suggests if d[0] == 1102]}
            elif avg_score < 30:
                result_dict[key] = {"average_score": avg_score, "name": "Health aspects",
                                    "description": "Refers to an individual`s physical health, including factors such as nutrition, exercise, and access to medical care.",
                                    "suggestions_text": [list(eval(d[1])) for d in suggests if d[0] == 1102]}

        elif key == 1103:
            if avg_score >= 66:
                result_dict[key] = {"average_score": avg_score, "name": "Time management",
                                    "description": "Refers to an individual`s ability to effectively manage their time and prioritize tasks to maximize productivity and reduce stress.",
                                    "suggestions_text": [list(eval(d[3])) for d in suggests if d[0] == 1103]}
            elif avg_score >= 30:
                result_dict[key] = {"average_score": avg_score, "name": "Time management",
                                    "description": "Refers to an individual`s ability to effectively manage their time and prioritize tasks to maximize productivity and reduce stress.",
                                    "suggestions_text": [list(eval(d[2])) for d in suggests if d[0] == 1103]}
            elif avg_score < 30:
                result_dict[key] = {"average_score": avg_score, "name": "Time management",
                                    "description": "Refers to an individual`s ability to effectively manage their time and prioritize tasks to maximize productivity and reduce stress.",
                                    "suggestions_text": [list(eval(d[1])) for d in suggests if d[0] == 1103]}

        elif key == 1104:
            if avg_score >= 66:
                result_dict[key] = {"average_score": avg_score, "name": "Educational standards",
                                    "description": "Refers to the quality of education provided in a given community, including factors such as curriculum, teaching quality, and access to resources.",
                                    "suggestions_text": [list(eval(d[3])) for d in suggests if d[0] == 1104]}
            elif avg_score >= 30:
                result_dict[key] = {"average_score": avg_score, "name": "Educational standards",
                                    "description": "Refers to the quality of education provided in a given community, including factors such as curriculum, teaching quality, and access to resources.",
                                    "suggestions_text": [list(eval(d[2])) for d in suggests if d[0] == 1104]}
            elif avg_score < 30:
                result_dict[key] = {"average_score": avg_score, "name": "Educational standards",
                                    "description": "Refers to the quality of education provided in a given community, including factors such as curriculum, teaching quality, and access to resources.",
                                    "suggestions_text": [list(eval(d[1])) for d in suggests if d[0] == 1104]}

        elif key == 1105:
            if avg_score >= 66:
                result_dict[key] = {"average_score": avg_score, "name": "Cultural diversity",
                                    "description": "Refers to the range of cultures, beliefs, and practices within a given community, and the level of acceptance and celebration of diversity.",
                                    "suggestions_text": [list(eval(d[3])) for d in suggests if d[0] == 1105]}
            elif avg_score >= 30:
                result_dict[key] = {"average_score": avg_score, "name": "Cultural diversity",
                                    "description": "Refers to the range of cultures, beliefs, and practices within a given community, and the level of acceptance and celebration of diversity.",
                                    "suggestions_text": [list(eval(d[2])) for d in suggests if d[0] == 1105]}
            elif avg_score < 30:
                result_dict[key] = {"average_score": avg_score, "name": "Cultural diversity",
                                    "description": "Refers to the range of cultures, beliefs, and practices within a given community, and the level of acceptance and celebration of diversity.",
                                    "suggestions_text": [list(eval(d[1])) for d in suggests if d[0] == 1105]}

        elif key == 1106:
            if avg_score >= 66:
                result_dict[key] = {"average_score": avg_score, "name": "Social well-being",
                                    "description": "Social well-being refers to the quality of an individual`s social interactions, relationships, and sense of community belonging.",
                                    "suggestions_text": [list(eval(d[3])) for d in suggests if d[0] == 1106]}
            elif avg_score >= 30:
                result_dict[key] = {"average_score": avg_score, "name": "Social well-being",
                                    "description": "Social well-being refers to the quality of an individual`s social interactions, relationships, and sense of community belonging.",
                                    "suggestions_text": [list(eval(d[2])) for d in suggests if d[0] == 1106]}
            elif avg_score < 30:
                result_dict[key] = {"average_score": avg_score, "name": "Social well-being",
                                    "description": "Social well-being refers to the quality of an individual`s social interactions, relationships, and sense of community belonging.",
                                    "suggestions_text": [list(eval(d[1])) for d in suggests if d[0] == 1106]}

        elif key == 1107:
            if avg_score >= 66:
                result_dict[key] = {"average_score": avg_score, "name": "Good governance",
                                    "description": "Refers to the effectiveness and transparency of governing systems and institutions in promoting the well-being of all members of a community.",
                                    "suggestions_text": [list(eval(d[3])) for d in suggests if d[0] == 1107]}
            elif avg_score >= 30:
                result_dict[key] = {"average_score": avg_score, "name": "Good governance",
                                    "description": "Refers to the effectiveness and transparency of governing systems and institutions in promoting the well-being of all members of a community.",
                                    "suggestions_text": [list(eval(d[2])) for d in suggests if d[0] == 1107]}
            elif avg_score < 30:
                result_dict[key] = {"average_score": avg_score, "name": "Good governance",
                                    "description": "Refers to the effectiveness and transparency of governing systems and institutions in promoting the well-being of all members of a community.",
                                    "suggestions_text": [list(eval(d[1])) for d in suggests if d[0] == 1107]}

        elif key == 1108:
            if avg_score >= 66:
                result_dict[key] = {"average_score": avg_score, "name": "Community vitality",
                                    "description": "Refers to the health and vibrancy of a community, including factors such as social cohesion, civic engagement, and access to resources.",
                                    "suggestions_text": [list(eval(d[3])) for d in suggests if d[0] == 1108]}
            elif avg_score >= 30:
                result_dict[key] = {"average_score": avg_score, "name": "Community vitality",
                                    "description": "Refers to the health and vibrancy of a community, including factors such as social cohesion, civic engagement, and access to resources.",
                                    "suggestions_text": [list(eval(d[2])) for d in suggests if d[0] == 1108]}
            elif avg_score < 30:
                result_dict[key] = {"average_score": avg_score, "name": "Community vitality",
                                    "description": "Refers to the health and vibrancy of a community, including factors such as social cohesion, civic engagement, and access to resources.",
                                    "suggestions_text": [list(eval(d[1])) for d in suggests if d[0] == 1108]}

    suggest_dict = dict(sorted(result_dict.items()))

    curr.execute(
        "SELECT `Questions`,`response`, `result`, `datetime` FROM `h_custom`, `h_assessments` WHERE `id`=%s AND `type`=%s AND h_custom.type = h_assessments.assessId",
        (session['id'], session['type'],))
    details = curr.fetchone()

    mysql.commit()
    curr.close()

    return render_template("result.html", ques=ques, res1=res[3], res2=res[4], res3=res[6], res4=res[5], res5=dyna, res6=response, res7=suggest_dict, res8=questions, res9=details)


@app.route('/logout')
def logout():
    app.config['MYSQL_DB'] = 'sql12673861'
    now = datetime.datetime.now()
    curo = mysql.cursor()
    if 'id' in session:
        curo.execute("INSERT INTO `h_session` (id, email, action, actionC, datetime) VALUES (%s, %s, %s, %s, %s)", (session['id'], session['email'], 'Logged Out - Session Terminated', 0, now,))
    else:
        curo.execute("INSERT INTO `h_session` (email, action, actionC, datetime) VALUES (%s, %s, %s, %s)", (session['email'], 'Logged Out - Session Terminated', 0, now,))

    mysql.commit()
    curo.close()
    session.clear()
    return redirect(url_for("home"))


@app.errorhandler(Exception)
def handle_error(error):
    app.logger.error(error)
    error_name = error.__class__.__name__
    message = f"{error_name}: {str(error)}"
    return render_template('error.html', message=message), 500


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