from flask import Blueprint, jsonify, request
from hivebee.logger import read_alerts
import json, os

api = Blueprint('api', __name__)


@api.route('/api/alerts')
def get_alerts():
    return jsonify(read_alerts())


@api.route('/api/status')
def get_status():
    alerts = read_alerts()
    return jsonify({
        'total': len(alerts),
        'critical': len([a for a in alerts if a.get('risk_level') == 'CRITICAL']),
        'high': len([a for a in alerts if a.get('risk_level') == 'HIGH']),
        'medium': len([a for a in alerts if a.get('risk_level') == 'MEDIUM']),
        'low': len([a for a in alerts if a.get('risk_level') == 'LOW']),
        'monitoring': True
    })


@api.route('/api/clear', methods=['POST'])
def clear_alerts():
    from hivebee import load_config
    config = load_config()
    base = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
    path = os.path.join(base, config['logging']['alerts_log'])
    open(path, 'w').close()
    return jsonify({'status': 'cleared'})


@api.route('/api/files')
def get_files():
    base = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
    path = os.path.join(base, 'logs', 'baseline.json')
    if not os.path.exists(path):
        return jsonify([])
    with open(path) as f:
        return jsonify(json.load(f).get('honeyfiles', []))
