"""
Contraintes de zone - GMAO College
Indisponibilite des salles (cours PRONOTE, horaires speciaux, etc.).
"""
from flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify
from flask_login import login_required
from ..extensions import db
from ..core.models.equipment import RoomConstraint
from ..core.models.college import Room, Building
from datetime import datetime, time

constraints_bp = Blueprint('constraints', __name__, url_prefix='/constraints', template_folder='templates')


@constraints_bp.route('/')
@login_required
def index():
    constraints = RoomConstraint.query.order_by(RoomConstraint.is_active.desc(), RoomConstraint.day_of_week).all()
    rooms = Room.query.order_by(Room.name).all()
    return render_template('constraints/index.html', constraints=constraints, rooms=rooms)


@constraints_bp.route('/new', methods=['GET', 'POST'])
@login_required
def create():
    rooms = Room.query.order_by(Room.name).all()
    if request.method == 'POST':
        c = RoomConstraint(
            room_id=request.form.get('room_id') or None,
            constraint_type=request.form.get('constraint_type', 'time'),
            day_of_week=int(request.form.get('day_of_week')) if request.form.get('day_of_week') else None,
            start_time=datetime.strptime(request.form.get('start_time'), '%H:%M').time() if request.form.get('start_time') else None,
            end_time=datetime.strptime(request.form.get('end_time'), '%H:%M').time() if request.form.get('end_time') else None,
            reason=request.form.get('reason', ''),
            source=request.form.get('source', 'manual'),
            is_active=request.form.get('is_active') == 'on',
            effective_date_start=datetime.strptime(request.form.get('effective_date_start'), '%Y-%m-%d').date() if request.form.get('effective_date_start') else None,
            effective_date_end=datetime.strptime(request.form.get('effective_date_end'), '%Y-%m-%d').date() if request.form.get('effective_date_end') else None,
        )
        db.session.add(c)
        db.session.commit()
        flash('Contrainte creee.', 'success')
        return redirect(url_for('constraints.index'))
    return render_template('constraints/form.html', constraint=None, rooms=rooms)


@constraints_bp.route('/<int:id>/edit', methods=['GET', 'POST'])
@login_required
def edit(id):
    c = RoomConstraint.query.get_or_404(id)
    rooms = Room.query.order_by(Room.name).all()
    if request.method == 'POST':
        c.room_id = request.form.get('room_id') or None
        c.constraint_type = request.form.get('constraint_type', 'time')
        c.day_of_week = int(request.form.get('day_of_week')) if request.form.get('day_of_week') else None
        c.start_time = datetime.strptime(request.form.get('start_time'), '%H:%M').time() if request.form.get('start_time') else None
        c.end_time = datetime.strptime(request.form.get('end_time'), '%H:%M').time() if request.form.get('end_time') else None
        c.reason = request.form.get('reason', '')
        c.source = request.form.get('source', 'manual')
        c.is_active = request.form.get('is_active') == 'on'
        c.effective_date_start = datetime.strptime(request.form.get('effective_date_start'), '%Y-%m-%d').date() if request.form.get('effective_date_start') else None
        c.effective_date_end = datetime.strptime(request.form.get('effective_date_end'), '%Y-%m-%d').date() if request.form.get('effective_date_end') else None
        db.session.commit()
        flash('Contrainte modifiee.', 'success')
        return redirect(url_for('constraints.index'))
    return render_template('constraints/form.html', constraint=c, rooms=rooms)


@constraints_bp.route('/<int:id>/delete', methods=['POST'])
@login_required
def delete(id):
    c = RoomConstraint.query.get_or_404(id)
    db.session.delete(c)
    db.session.commit()
    flash('Contrainte supprimee.', 'success')
    return redirect(url_for('constraints.index'))


@constraints_bp.route('/api/room/<int:room_id>/availability')
@login_required
def room_availability(room_id):
    """Retourne les contraintes d'une salle."""
    date_str = request.args.get('date')
    check_date = datetime.strptime(date_str, '%Y-%m-%d').date() if date_str else None
    constraints = RoomConstraint.query.filter(
        db.or_(RoomConstraint.room_id == room_id, RoomConstraint.room_id.is_(None)),
        RoomConstraint.is_active == True
    ).all()
    result = []
    for c in constraints:
        if check_date and not c.applies_to_date(check_date):
            continue
        result.append({
            'id': c.id,
            'type': c.constraint_type,
            'day': c.day_name,
            'start': c.start_time.strftime('%H:%M') if c.start_time else None,
            'end': c.end_time.strftime('%H:%M') if c.end_time else None,
            'reason': c.reason or '',
            'source': c.source,
        })
    return jsonify({'constraints': result})