import io
import base64
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
from flask import Blueprint, jsonify

bp = Blueprint('vulnerability', __name__, url_prefix='/api/vulnerability')


def generate_drought_index_chart():
    """월별 가뭄 지수 차트 생성"""
    fig, ax = plt.subplots(figsize=(6, 3))

    np.random.seed(2025)
    months = list(range(1, 21))
    values_2025 = np.random.uniform(20, 35, 20)
    values_2024 = np.random.uniform(15, 30, 20)

    ax.plot(months, values_2025, 'b-', linewidth=2, label='2025')
    ax.plot(months, values_2024, 'g-', linewidth=2, label='2024')
    ax.set_xlim(1, 20)
    ax.set_ylim(10, 40)
    ax.set_xlabel('')
    ax.set_ylabel('')
    ax.legend(loc='lower right', fontsize=8)
    ax.grid(True, alpha=0.3)

    plt.tight_layout()
    buf = io.BytesIO()
    fig.savefig(buf, format='png', dpi=100, bbox_inches='tight', transparent=True)
    buf.seek(0)
    image_base64 = base64.b64encode(buf.getvalue()).decode('utf-8')
    plt.close(fig)

    return image_base64


def generate_rainfall_chart():
    """강우량 차트 생성"""
    fig, ax = plt.subplots(figsize=(6, 3))

    categories = ['누적강우', '평년누적', '평년대비']
    values = [75, 60, 85]
    colors = ['#3498db', '#2ecc71', '#9b59b6']

    bars = ax.barh(categories, values, color=colors, height=0.5)
    ax.set_xlim(0, 100)
    ax.set_xlabel('')

    for bar, val in zip(bars, values):
        ax.text(val + 2, bar.get_y() + bar.get_height()/2, f'{val}%',
                va='center', fontsize=9)

    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)

    plt.tight_layout()
    buf = io.BytesIO()
    fig.savefig(buf, format='png', dpi=100, bbox_inches='tight', transparent=True)
    buf.seek(0)
    image_base64 = base64.b64encode(buf.getvalue()).decode('utf-8')
    plt.close(fig)

    return image_base64


@bp.route('/drought-index', methods=['GET'])
def drought_index():
    """월별 가뭄 지수 차트 반환"""
    try:
        image = generate_drought_index_chart()
        return jsonify({
            'status': 'success',
            'image': image
        })
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': str(e),
            'image': None
        })


@bp.route('/rainfall', methods=['GET'])
def rainfall():
    """강우량 차트 반환"""
    try:
        image = generate_rainfall_chart()
        return jsonify({
            'status': 'success',
            'image': image
        })
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': str(e),
            'image': None
        })


@bp.route('/summary', methods=['GET'])
def summary():
    """취약성 요약 데이터 반환"""
    return jsonify({
        'status': 'success',
        'data': {
            'risk_level': '심각',
            'risk_score': 72,
            'drought': {'value': 72, 'risk': 'High'},
            'soil_moisture': {'value': 45, 'risk': 'Moderate'},
            'reservoir': {'value': 27, 'risk': 'Low'}
        }
    })
