from flask import Blueprint, request, jsonify
from oletools import olevba, mraptor
from utils.file_handler import allowed_file, save_file, delete_file

mraptor_bp = Blueprint('mraptor', __name__)

@mraptor_bp.route('/analyze', methods=['POST'])
def analyze_mraptor():
    if 'file' not in request.files:
        return jsonify({'error': 'No file uploaded'}), 400

    file = request.files['file']
    if file.filename == '' or not allowed_file(file.filename):
        return jsonify({'error': 'Invalid or unsupported file type'}), 400

    filepath = save_file(file)

    # Analyze with olevba
    vbaparser = olevba.VBA_Parser(filepath)
    if vbaparser.detect_vba_macros():
        vba_code = ''
        try:
            vba_code = vbaparser.get_vba_code_all_modules()
        except Exception as e:
            delete_file(filepath)
            return jsonify({'error': e})
        delete_file(filepath)
        raptor = mraptor.MacroRaptor(vba_code)
        raptor.scan()
        if raptor.suspicious:
            return jsonify({'filename': file.filename, 'result': mraptor.Result_Suspicious, 'flags': raptor.get_flags(), 'matches': raptor.matches})
        else: 
            return jsonify({'filename': file.filename, 'result': mraptor.Result_MacroOK, 'flags': raptor.get_flags(), 'matches': raptor.matches})
    else:
        delete_file(filepath)
        return jsonify({'filename': file.filename, 'result': mraptor.Result_NoMacro})
