"""Equipments Scheduled 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 app_new.constants import EQUIPMENT_STATUSES

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

scheduled_bp = Blueprint("equipments_scheduled", __name__, template_folder='templates')

@scheduled_bp.route('/<int:id>/scheduled-tasks')
@login_required
def scheduled_tasks(id):
    """Liste des tâches planifiées pour un équipement."""
    from ..core.models.planning import ScheduledTask
    from ..core.models.equipment import Equipment
    
    equipment = Equipment.query.get_or_404(id)
    tasks = ScheduledTask.query.filter_by(equipment_id=id).order_by(ScheduledTask.scheduled_date).all()
    
    return render_template('equipments/scheduled_tasks.html', equipment=equipment, tasks=tasks)


@scheduled_bp.route('/<int:id>/scheduled-tasks/new', methods=['GET', 'POST'])
@login_required
def new_scheduled_task(id):
    """Ajouter une tâche planifiée à un équipement."""
    from ..core.models.planning import ScheduledTask
    from ..core.models.equipment import Equipment
    from ..core.models.college import Room
    from flask_login import current_user
    from datetime import datetime
    
    equipment = Equipment.query.get_or_404(id)
    
    if request.method == 'POST':
        # Si company_id est défini, pas de technicien individuel
        assigned_to = request.form.get('assigned_to_id') or None
        company = request.form.get('company_id') or None
        
        task = ScheduledTask(
            equipment_id=id,
            preventive_task_id=request.form.get('preventive_task_id') or None,
            room_id=request.form.get('room_id') or None,
            scheduled_date=datetime.strptime(request.form.get('scheduled_date'), '%Y-%m-%d').date() if request.form.get('scheduled_date') else None,
            scheduled_start=datetime.strptime(request.form.get('scheduled_start'), '%H:%M').time() if request.form.get('scheduled_start') else None,
            scheduled_end=datetime.strptime(request.form.get('scheduled_end'), '%H:%M').time() if request.form.get('scheduled_end') else None,
            estimated_duration=int(request.form.get('estimated_duration') or 30),
            status='planned',
            assigned_to_id=assigned_to,
            company_id=company
        )
        db.session.add(task)
        db.session.commit()
        flash('Tâche planifiée ajoutée', 'success')
        return redirect(url_for('equipments.scheduled_tasks', id=id))
    
    from ..core.models.company import Company
    from ..core.models.user import User
    
    rooms = Room.query.order_by(Room.name).all()
    technicians = User.query.filter(User.role.in_(['technicien', 'tech', 'technician', 'responsable_gmao', 'admin'])).all()
    companies = Company.query.order_by(Company.name).all()
    return render_template('equipments/scheduled_task_form.html', equipment=equipment, rooms=rooms, technicians=technicians, companies=companies)


@scheduled_bp.route('/<int:id>/scheduled-tasks/<int:task_id>/edit', methods=['GET', 'POST'])
@login_required
def edit_scheduled_task(id, task_id):
    """Modifier une tâche planifiée."""
    from ..core.models.planning import ScheduledTask
    from ..core.models.college import Room
    from datetime import datetime
    
    task = ScheduledTask.query.filter_by(id=task_id, equipment_id=id).first_or_404()
    equipment = Equipment.query.get_or_404(id)
    
    if request.method == 'POST':
        task.preventive_task_id = request.form.get('preventive_task_id') or None
        task.room_id = request.form.get('room_id') or None
        task.scheduled_date = datetime.strptime(request.form.get('scheduled_date'), '%Y-%m-%d').date() if request.form.get('scheduled_date') else None
        task.scheduled_start = datetime.strptime(request.form.get('scheduled_start'), '%H:%M').time() if request.form.get('scheduled_start') else None
        task.scheduled_end = datetime.strptime(request.form.get('scheduled_end'), '%H:%M').time() if request.form.get('scheduled_end') else None
        task.estimated_duration = int(request.form.get('estimated_duration') or 30)
        task.status = request.form.get('status', 'planned')
        task.notes = request.form.get('notes')
        task.assigned_to_id = request.form.get('assigned_to_id') or None
        task.company_id = request.form.get('company_id') or None
        db.session.commit()
        flash('Tâche mise à jour', 'success')
        return redirect(url_for('equipments.scheduled_tasks', id=id))
    
    from ..core.models.company import Company
    from ..core.models.user import User
    
    rooms = Room.query.order_by(Room.name).all()
    technicians = User.query.filter(User.role.in_(['technicien', 'tech', 'technician', 'responsable_gmao', 'admin'])).all()
    companies = Company.query.order_by(Company.name).all()
    return render_template('equipments/scheduled_task_form.html', equipment=equipment, task=task, rooms=rooms, technicians=technicians, companies=companies)


@scheduled_bp.route('/<int:id>/scheduled-tasks/<int:task_id>/delete', methods=['POST'])
@login_required
def delete_scheduled_task(id, task_id):
    """Supprimer une tâche planifiée."""
    from ..core.models.planning import ScheduledTask
    
    task = ScheduledTask.query.filter_by(id=task_id, equipment_id=id).first_or_404()
    db.session.delete(task)
    db.session.commit()
    flash('Tâche supprimée', 'success')
    return redirect(url_for('equipments.scheduled_tasks', id=id))


@scheduled_bp.route('/<int:id>/scheduled-tasks/<int:task_id>/create-intervention', methods=['GET', 'POST'])
@login_required
def create_intervention_from_task(id, task_id):
    """Créer une intervention à partir d'une tâche planifiée."""
    from ..core.models.planning import ScheduledTask
    from ..core.models.maintenance import Intervention
    from ..core.models.company import Company
    from ..core.models.user import User
    from flask_login import current_user
    
    task = ScheduledTask.query.filter_by(id=task_id, equipment_id=id).first_or_404()
    equipment = Equipment.query.get_or_404(id)
    
    if request.method == 'POST':
        intervention = Intervention(
            title=f"Intervention: {task.preventive_task.name if task.preventive_task else task.lot_task.name}",
            description=task.notes,
            equipment_id=id,
            room_id=request.form.get('room_id') or task.room_id,
            type='preventif',
            workflow_type='preventive',
            status='en_cours',
            scheduled_date=task.scheduled_date,
            scheduled_start=request.form.get('scheduled_start') or task.scheduled_start.strftime('%H:%M') if task.scheduled_start else None,
            scheduled_end=request.form.get('scheduled_end') or task.scheduled_end.strftime('%H:%M') if task.scheduled_end else None,
            assigned_to_id=request.form.get('assigned_to_id') or task.assigned_to_id or current_user.id
        )
        db.session.add(intervention)
        db.session.commit()
        flash('Intervention créée', 'success')
        return redirect(url_for('interventions.detail', id=intervention.id))
    
    rooms = Room.query.order_by(Room.name).all()
    technicians = User.query.filter(User.role.in_(['technician', 'admin'])).all()
    companies = Company.query.order_by(Company.name).all()
    
    return render_template('interventions/form.html', 
                          equipment=equipment, 
                          task=task,
                          rooms=rooms, 
                          technicians=technicians, 
                          companies=companies)
