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

olevba_bp = Blueprint('olevba', __name__)

@olevba_bp.route('/analyze', methods=['POST'])
def analyze_vba():
    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 = oletools.olevba.VBA_Parser(filepath)
    results = vbaparser.analyze_macros()
    delete_file(filepath)
    

    return jsonify({'filename': file.filename, 'macros': results})
