"""
Meters Routes - GMAO Collège
Gestion des compteurs
"""
from flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify
from flask_login import login_required, current_user
from app_new.extensions import db
from app_new.core.models.planning import Meter, MeterReading
from app_new.core.models.equipment import Equipment

meters_bp = Blueprint('meters', __name__, template_folder='templates')


@meters_bp.route('/')
@login_required
def index():
    """Liste de tous les compteurs."""
    # Récupérer tous les compteurs avec leur équipement
    meters = Meter.query.join(Equipment).order_by(Equipment.name, Meter.name).all()
    
    # Statistiques
    total_count = len(meters)
    warning_count = sum(1 for m in meters if m.warning_level == 'warning')
    critical_count = sum(1 for m in meters if m.warning_level == 'critical')
    maintenance_count = sum(1 for m in meters if m.warning_level == 'maintenance')
    
    return render_template('meters/index.html',
                         meters=meters,
                         total_count=total_count,
                         warning_count=warning_count,
                         critical_count=critical_count,
                         maintenance_count=maintenance_count)


@meters_bp.route('/<int:meter_id>')
@login_required
def detail(meter_id):
    """Détails d'un compteur avec historique des relevés."""
    meter = Meter.query.get_or_404(meter_id)
    readings = MeterReading.query.filter_by(meter_id=meter_id)\
        .order_by(MeterReading.reading_date.desc()).limit(50).all()
    
    return render_template('meters/detail.html', meter=meter, readings=readings)


@meters_bp.route('/<int:meter_id>/reading', methods=['POST'])
@login_required
def add_reading(meter_id):
    """Ajouter un relevé à un compteur."""
    meter = Meter.query.get_or_404(meter_id)
    
    try:
        value = float(request.form.get('value'))
    except (TypeError, ValueError):
        return jsonify({'success': False, 'error': 'Valeur invalide'}), 400
    
    is_reset = request.form.get('is_reset') == '1'
    reset_reason = (request.form.get('reset_reason') or '').strip()
    if value < (meter.current_value or 0) and not (is_reset and reset_reason):
        flash('Un relevé inférieur exige de cocher « remise à zéro » et de saisir un motif.', 'danger')
        return redirect(url_for('meters.detail', meter_id=meter_id))
    if is_reset and not reset_reason:
        flash('Le motif de remise à zéro est obligatoire.', 'danger')
        return redirect(url_for('meters.detail', meter_id=meter_id))

    reading = MeterReading(
        meter_id=meter_id,
        value=value,
        read_by_id=current_user.id,
        notes=request.form.get('notes', ''), is_reset=is_reset, reset_reason=reset_reason or None,
    )
    meter.current_value = value
    if is_reset:
        meter.initial_value = value
        meter.last_maintenance_value = value
    meter.updated_at = db.func.now()
    
    db.session.add(reading)
    db.session.commit()
    
    flash(f'Relevé enregistré: {value} {meter.unit}', 'success')
    return redirect(url_for('meters.detail', meter_id=meter_id))


@meters_bp.route('/<int:meter_id>/edit', methods=['GET', 'POST'])
@login_required
def edit(meter_id):
    """Modifier un compteur."""
    from datetime import datetime, timedelta, date
    
    meter = Meter.query.get_or_404(meter_id)
    equipments = Equipment.query.filter_by(is_group=False).order_by(Equipment.name).all()
    
    if request.method == 'POST':
        meter.name = request.form.get('name')
        meter.meter_type = request.form.get('meter_type', 'hours')
        meter.unit = request.form.get('unit', 'h')
        meter.warning_threshold = request.form.get('warning_threshold', type=float)
        meter.critical_threshold = request.form.get('critical_threshold', type=float)
        meter.maintenance_interval = request.form.get('maintenance_interval', type=float)
        meter.last_maintenance_value = request.form.get('last_maintenance_value', type=float)
        meter.reading_interval_days = request.form.get('reading_interval_days', type=int)
        meter.current_value = request.form.get('current_value', type=float, default=0)
        
        # Date du dernier relevé
        last_reading_date = request.form.get('last_reading_date')
        if last_reading_date:
            meter.last_reading_date = datetime.strptime(last_reading_date, '%Y-%m-%d').date()
        else:
            meter.last_reading_date = None
        
        # Équipement
        equipment_id = request.form.get('equipment_id')
        if equipment_id:
            meter.equipment_id = int(equipment_id)
        
        db.session.commit()
        flash('Compteur modifié avec succès', 'success')
        return redirect(url_for('meters.detail', meter_id=meter_id))
    
    return render_template('meters/edit.html', 
                          meter=meter, 
                          equipments=equipments,
                          timedelta=timedelta,
                          today=date.today())
