import os
from flask import Flask, render_template, request, redirect, url_for
import xml.etree.ElementTree as ET

app = Flask(__name__)

def load_questions():
    file_path = os.path.join(os.path.dirname(__file__), 'questions.xml')
    tree = ET.parse(file_path)
    root = tree.getroot()
    questions = []
    for question_elem in root.findall('question'):
        q_id = question_elem.get('id')
        category = question_elem.get('category')
        text = question_elem.find('text').text
        questions.append({'id': q_id, 'category': category, 'text': text})
    return questions

questions = load_questions()

@app.route('/')
def index():
    return render_template('index.html', questions=questions)

@app.route('/submit', methods=['POST'])
def submit():
    scores = {'D': 0, 'I': 0, 'S': 0, 'C': 0}
    
    for question in questions:
        answer = request.form.get(f'q{question["id"]}')
        if answer and answer.isdigit():
            scores[question['category']] += int(answer)
    
    max_type = max(scores, key=scores.get)
    return render_template('result.html', 
                          personality=max_type,
                          scores=scores)

if __name__ == '__main__':
    app.run(debug=True)