from datetime import date
from flask import Blueprint, flash, redirect, render_template, request, url_for
from flask_login import current_user, login_required
from ..extensions import db
from ..core.models import WorkRequest, WorkRequestEvent, WorkRequestQuote, Equipment, Company, Service

works_bp = Blueprint("works", __name__, template_folder="templates")

STATUSES = ["brouillon", "à_valider_chef", "travaux_internes_autorisés", "devis_en_attente", "devis_à_valider_chef", "devis_accepté", "envoyée_département", "entreprise_mandatée", "travaux_planifiés", "travaux_en_cours", "travaux_terminés", "clôturée", "refusée"]

@works_bp.route("/")
@login_required
def index():
    flash("Les demandes de travaux sont désormais gérées directement dans les interventions.", "info")
    return redirect(url_for("interventions.index"))

@works_bp.route("/new", methods=["GET", "POST"])
@login_required
def new():
    if request.method == "GET":
        flash("Créez une intervention puis choisissez son workflow travaux dans sa fiche.", "info")
        return redirect(url_for("interventions.create", workflow="travaux"))
    if request.method == "POST":
        item = WorkRequest(title=request.form["title"].strip(), description=request.form["description"].strip(), execution_mode=request.form.get("execution_mode", "interne"), priority=request.form.get("priority", "normale"), equipment_id=request.form.get("equipment_id", type=int) or None, created_by_id=current_user.id, status="à_valider_chef")
        db.session.add(item); db.session.flush(); db.session.add(WorkRequestEvent(request=item, user_id=current_user.id, new_status=item.status, comment="Demande créée")); db.session.commit(); flash("Demande de travaux créée.", "success"); return redirect(url_for("works.detail", id=item.id))
    return render_template("works/form.html", equipments=Equipment.query.filter_by(is_deleted=False).order_by(Equipment.name).all())

@works_bp.route("/<int:id>", methods=["GET", "POST"])
@login_required
def detail(id):
    # Compatibilité avec les anciennes URLs : le nouveau suivi est dans l'intervention.
    flash("Le suivi des travaux est désormais intégré aux interventions.", "info")
    return redirect(url_for("interventions.index"))
    item = WorkRequest.query.get_or_404(id)
    if request.method == "POST":
        old = item.status; item.status = request.form.get("status", old); item.notes = request.form.get("notes") or item.notes; item.company_id = request.form.get("company_id", type=int) or item.company_id; item.service_id = request.form.get("service_id", type=int) or item.service_id
        if item.status != old: db.session.add(WorkRequestEvent(request=item, user_id=current_user.id, old_status=old, new_status=item.status, comment=request.form.get("comment")))
        db.session.commit(); flash("Demande mise à jour.", "success"); return redirect(url_for("works.detail", id=id))
    return render_template("works/detail.html", item=item, statuses=STATUSES, companies=Company.query.order_by(Company.name).all(), services=Service.query.order_by(Service.name).all())
