"""Malware Sandbox routes."""
import os
from flask import Blueprint, request, jsonify, render_template, current_app
from web.auth import login_required

malware_sandbox_bp = Blueprint('malware_sandbox', __name__, url_prefix='/sandbox')

def _get_sandbox():
    from modules.malware_sandbox import get_sandbox
    return get_sandbox()

@malware_sandbox_bp.route('/')
@login_required
def index():
    return render_template('malware_sandbox.html')

@malware_sandbox_bp.route('/status')
@login_required
def status():
    return jsonify(_get_sandbox().get_status())

@malware_sandbox_bp.route('/submit', methods=['POST'])
@login_required
def submit():
    sb = _get_sandbox()
    if request.content_type and 'multipart' in request.content_type:
        f = request.files.get('sample')
        if not f:
            return jsonify({'ok': False, 'error': 'No file uploaded'})
        upload_dir = current_app.config.get('UPLOAD_FOLDER', '/tmp')
        filepath = os.path.join(upload_dir, f.filename)
        f.save(filepath)
        return jsonify(sb.submit_sample(filepath, f.filename))
    else:
        data = request.get_json(silent=True) or {}
        return jsonify(sb.submit_sample(data.get('path', ''), data.get('name')))

@malware_sandbox_bp.route('/samples')
@login_required
def samples():
    return jsonify(_get_sandbox().list_samples())

@malware_sandbox_bp.route('/static', methods=['POST'])
@login_required
def static_analysis():
    data = request.get_json(silent=True) or {}
    return jsonify(_get_sandbox().static_analysis(data.get('path', '')))

@malware_sandbox_bp.route('/dynamic', methods=['POST'])
@login_required
def dynamic_analysis():
    data = request.get_json(silent=True) or {}
    job_id = _get_sandbox().dynamic_analysis(data.get('path', ''), data.get('timeout', 60))
    return jsonify({'ok': bool(job_id), 'job_id': job_id})

@malware_sandbox_bp.route('/report', methods=['POST'])
@login_required
def generate_report():
    data = request.get_json(silent=True) or {}
    return jsonify(_get_sandbox().generate_report(data.get('path', '')))

@malware_sandbox_bp.route('/reports')
@login_required
def reports():
    return jsonify(_get_sandbox().list_reports())

@malware_sandbox_bp.route('/job/<job_id>')
@login_required
def job_status(job_id):
    job = _get_sandbox().get_job(job_id)
    return jsonify(job or {'error': 'Job not found'})
