"""Equipments Documents Routes - GMAO Collège"""
from flask import Blueprint, render_template, redirect, url_for, request, flash, jsonify, current_app
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 app_new.constants import EQUIPMENT_STATUSES
from uuid import uuid4

ALLOWED_DOCUMENT_EXTENSIONS = {
    'pdf', 'png', 'jpg', 'jpeg', 'gif', 'doc', 'docx', 'xls', 'xlsx'
}


def _allowed_document(filename):
    return (
        '.' in filename
        and filename.rsplit('.', 1)[1].lower() in ALLOWED_DOCUMENT_EXTENSIONS
    )

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

documents_bp = Blueprint("equipments_documents", __name__, template_folder='templates')

@documents_bp.route('/<int:id>/documents/upload', methods=['POST'])
@login_required
def upload_document(id):
    """Téléverser un document pour un équipement."""
    equipment = Equipment.query.get_or_404(id)
    
    if 'file' not in request.files:
        return jsonify({'success': False, 'error': 'Aucun fichier'})
    
    file = request.files['file']
    if file.filename == '':
        return jsonify({'success': False, 'error': 'Aucun fichier sélectionné'})

    if not _allowed_document(file.filename):
        return jsonify({'success': False, 'error': 'Type de fichier non autorisé'}), 400
    
    import os
    from werkzeug.utils import secure_filename
    
    original_filename = secure_filename(file.filename)
    extension = original_filename.rsplit('.', 1)[1].lower()
    filename = f'{uuid4().hex}.{extension}'
    upload_dir = os.path.join(
        current_app.config['UPLOAD_FOLDER'], 'documents', str(id)
    )
    os.makedirs(upload_dir, exist_ok=True)
    filepath = os.path.join(upload_dir, filename)
    file.save(filepath)
    
    doc = EquipmentDocument(
        equipment_id=id,
        filename=original_filename,
        filepath=filepath,
        description=request.form.get('description'),
        document_type=request.form.get('document_type') or 'autre',
        uploaded_by_id=current_user.id
    )
    db.session.add(doc)
    db.session.commit()
    
    return jsonify({'success': True, 'doc_id': doc.id})


@documents_bp.route('/documents/<int:doc_id>/download')
@login_required
def download_document(doc_id):
    """Télécharger un document."""
    doc = EquipmentDocument.query.get_or_404(doc_id)
    from flask import send_file
    return send_file(doc.filepath, as_attachment=True, download_name=doc.filename)


@documents_bp.route('/documents/<int:doc_id>/delete', methods=['POST'])
@login_required
def delete_document(doc_id):
    """Supprimer un document."""
    doc = EquipmentDocument.query.get_or_404(doc_id)
    import os
    if os.path.exists(doc.filepath):
        os.remove(doc.filepath)
    db.session.delete(doc)
    db.session.commit()
    return jsonify({'success': True})


# ==================== RESTRICTIONS ====================
