"""Equipments Meters Routes - GMAO Collège"""
from flask import Blueprint, render_template, redirect, url_for, request, flash, jsonify
from flask_login import login_required, current_user
from datetime import datetime
from app_new.extensions import db
from ..core.models.equipment import Equipment, EquipmentCategory, EquipmentDocument, EquipmentRoomHistory, EquipmentRestriction
from ..core.models.college import Room, Building, RoomType, Zone
from ..core.models.maintenance import Lot, Intervention
from ..core.models.planning import Meter, MeterReading, Consumable, EquipmentConsumable, ScheduledTask
from ..core.services.meter_service import MeterDomainError, create_meter, record_meter_reading
from app_new.constants import EQUIPMENT_STATUSES

def _empty_to_none(v):
    """Convertit une chaîne vide en None."""
    return None if v == '' else v

meters_bp = Blueprint("equipments_meters", __name__, template_folder='templates')

@meters_bp.route('/lots')
@login_required
def lots():
    """Liste des lots."""
    lots = Lot.query.order_by(Lot.name).all()
    categories = EquipmentCategory.query.order_by(EquipmentCategory.name).all()
    return render_template('equipments/lots.html', title='Lots', lots=lots, categories=categories)


@meters_bp.route('/lots/new', methods=['GET', 'POST'])
@login_required
def create_lot():
    """Créer un lot."""
    categories = EquipmentCategory.query.order_by(EquipmentCategory.name).all()
    
    if request.method == 'POST':
        lot = Lot(
            name=request.form.get('name'),
            category_id=request.form.get('category_id') or None
        )
        db.session.add(lot)
        db.session.commit()
        flash(f"Lot '{lot.name}' créé.", 'success')
        return redirect(url_for('equipments_meters.lots'))
    return render_template('equipments/lot_form.html',
                          title='Nouveau lot', categories=categories)


@meters_bp.route('/lots/<int:id>', methods=['GET', 'POST'])
@login_required
def lot_detail(id):
    """Détails et modification d'un lot."""
    lot = Lot.query.get_or_404(id)
    categories = EquipmentCategory.query.order_by(EquipmentCategory.name).all()
    
    # Récupérer les équipements de ce lot
    equipments = Equipment.query.filter_by(lot_id=id).order_by(Equipment.name).all()
    
    if request.method == 'POST':
        lot.name = request.form.get('name')
        lot.category_id = request.form.get('category_id') or None
        db.session.commit()
        flash(f"Lot '{lot.name}' modifié.", 'success')
        return redirect(url_for('equipments_meters.lots'))
    return render_template('equipments/lot_detail.html', 
                          title=f'Lot: {lot.name}', 
                          lot=lot, 
                          categories=categories,
                          equipments=equipments)


# ==================== MÈTRES ====================

@meters_bp.route('/<int:id>/meters/add', methods=['POST'])
@login_required
def add_meter(id):
    """Ajouter un compteur à un équipement."""
    equipment = Equipment.query.get_or_404(id)
    
    meter = create_meter(
        name=request.form.get('name'),
        meter_type=request.form.get('meter_type', 'hours'),
        unit=request.form.get('unit', 'h'),
        initial_value=float(request.form.get('initial_value', 0) or 0),
        current_value=float(request.form.get('current_value', 0) or 0),
        warning_threshold=float(request.form.get('warning_threshold')) if request.form.get('warning_threshold') else None,
        critical_threshold=float(request.form.get('critical_threshold')) if request.form.get('critical_threshold') else None,
        maintenance_interval=float(request.form.get('maintenance_interval')) if request.form.get('maintenance_interval') else None,
        last_maintenance_value=float(request.form.get('last_maintenance_value')) if request.form.get('last_maintenance_value') else None,
        equipment_id=id,
    )
    
    return jsonify({'success': True, 'meter_id': meter.id})


@meters_bp.route('/<int:id>/meters/reading', methods=['POST'])
@login_required
def add_meter_reading(id):
    """Ajouter un relevé de compteur."""
    data = request.get_json()
    meter_id = data.get('meter_id')
    value = data.get('value')
    
    meter = Meter.query.get_or_404(meter_id)
    if meter.equipment_id != id:
        from flask import abort
        abort(404)
    try:
        reading = record_meter_reading(
            meter=meter, value=value, user_id=current_user.id,
            notes=data.get('notes'), is_reset=bool(data.get('is_reset')),
            reset_reason=data.get('reset_reason'), commit=True,
        )
    except MeterDomainError as exc:
        db.session.rollback()
        return jsonify({'success': False, 'error': str(exc)}), 400

    return jsonify({'success': True, 'reading_id': reading.id})


# ==================== CONSOMMABLES ====================

@meters_bp.route('/<int:id>/consumables/add', methods=['POST'])
@login_required
def add_consumable(id):
    """Associer un consommable à un équipement."""
    equipment = Equipment.query.get_or_404(id)
    
    ec = EquipmentConsumable(
        equipment_id=id,
        consumable_id=request.form.get('consumable_id'),
        replacement_interval_days=int(request.form.get('replacement_interval_days')) if request.form.get('replacement_interval_days') else None,
        replacement_interval_hours=int(request.form.get('replacement_interval_hours')) if request.form.get('replacement_interval_hours') else None,
        replacement_interval_cycles=int(request.form.get('replacement_interval_cycles')) if request.form.get('replacement_interval_cycles') else None,
        notes=request.form.get('notes')
    )
    db.session.add(ec)
    db.session.commit()
    
    return jsonify({'success': True, 'ec_id': ec.id})


@meters_bp.route('/<int:id>/consumables/remove', methods=['POST'])
@login_required
def remove_consumable(id):
    """Retirer un consommable d'un équipement."""
    data = request.get_json()
    ec_id = data.get('ec_id')
    
    ec = EquipmentConsumable.query.filter_by(id=ec_id, equipment_id=id).first_or_404()
    db.session.delete(ec)
    db.session.commit()
    
    return jsonify({'success': True})


# ==================== DOCUMENTS ====================
