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('terrain', __name__, url_prefix='/api/terrain')


def generate_simulation_chart():
    """시간별 수위 변화 차트 생성"""
    fig, ax = plt.subplots(figsize=(5, 2.5))

    np.random.seed(int(np.random.random() * 1000))
    days = list(range(1, 15))
    water_level = 100 - np.cumsum(np.random.uniform(2, 8, 14))
    water_level = np.maximum(water_level, 20)

    ax.fill_between(days, water_level, alpha=0.3, color='#3498db')
    ax.plot(days, water_level, 'b-', linewidth=2, marker='o', markersize=4)

    ax.axhline(y=40, color='#e74c3c', linestyle='--', linewidth=1.5, label='경고 수위')
    ax.set_xlim(1, 14)
    ax.set_ylim(0, 100)
    ax.set_xlabel('일자', fontsize=9)
    ax.set_ylabel('수위 (%)', fontsize=9)
    ax.legend(loc='upper 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


@bp.route('/simulation-chart', methods=['GET'])
def simulation_chart():
    """시뮬레이션 차트 반환"""
    try:
        image = generate_simulation_chart()
        return jsonify({
            'status': 'success',
            'image': image
        })
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': str(e),
            'image': None
        })


@bp.route('/simulation-data', methods=['GET'])
def simulation_data():
    """시뮬레이션 데이터 반환"""
    return jsonify({
        'status': 'success',
        'data': {
            'water_shortage': 3672,
            'farm_damage': 2803,
            'estimated_cost': 12.5,
            'risk_level': '심각'
        }
    })
