"""
Exports PDF - GMAO Collège
Generation de rapports d'interventions en PDF simple (HTML -> print).
"""
from flask import Blueprint, render_template, make_response, request
from flask_login import login_required
from datetime import datetime, date, timedelta, timezone
from app_new.extensions import db

exports_bp = Blueprint('exports', __name__, template_folder='templates')


@exports_bp.route('/exports/interventions')
@login_required
def export_interventions():
    """Export des interventions en HTML imprimable (ctrl+P -> PDF)."""
    from app_new.core.models.maintenance import Intervention
    from app_new.constants import INTERVENTION_STATUSES
    
    # Filtres
    status = request.args.get('status', '')
    date_from = request.args.get('from', '')
    date_to = request.args.get('to', '')
    
    query = Intervention.query
    if status:
        query = query.filter_by(status=status)
    if date_from:
        try:
            query = query.filter(Intervention.created_at >= datetime.fromisoformat(date_from))
        except ValueError:
            pass
    if date_to:
        try:
            query = query.filter(Intervention.created_at <= datetime.fromisoformat(date_to))
        except ValueError:
            pass
    
    interventions = query.order_by(Intervention.created_at.desc()).all()
    
    html = render_template('exports/interventions.html',
                          interventions=interventions,
                          statuses=INTERVENTION_STATUSES,
                          filters={'status': status, 'from': date_from, 'to': date_to},
                          generated_at=datetime.now(timezone.utc))
    
    response = make_response(html)
    response.headers['Content-Type'] = 'text/html; charset=utf-8'
    return response


@exports_bp.route('/exports/interventions/csv')
@login_required
def export_interventions_csv():
    """Export des interventions en CSV."""
    from app_new.core.models.maintenance import Intervention
    
    query = Intervention.query
    status = request.args.get('status', '')
    if status:
        query = query.filter_by(status=status)
    
    interventions = query.order_by(Intervention.created_at.desc()).all()
    
    import csv
    import io
    output = io.StringIO()
    writer = csv.writer(output, delimiter=';')
    writer.writerow(['ID', 'Titre', 'Type', 'Statut', 'Priorite', 'Date creation', 'Date debut', 'Date fin', 'Equipement', 'Salle'])
    
    for i in interventions:
        writer.writerow([
            i.id, i.title or '', i.type or '', i.status or '', i.priority or '',
            i.created_at.strftime('%d/%m/%Y %H:%M') if i.created_at else '',
            i.started_at.strftime('%d/%m/%Y %H:%M') if i.started_at else '',
            i.completed_at.strftime('%d/%m/%Y %H:%M') if i.completed_at else '',
            i.equipment.name if i.equipment else '',
            i.room.name if i.room else '',
        ])
    
    response = make_response(output.getvalue())
    response.headers['Content-Type'] = 'text/csv; charset=utf-8'
    response.headers['Content-Disposition'] = 'attachment; filename=interventions_export.csv'
    return response


@exports_bp.route('/exports/costs/csv')
@login_required
def export_costs_csv():
    """Export consolidé des coûts de maintenance, contrats et valeur du stock."""
    import csv
    import io
    from app_new.core.models.maintenance import Intervention
    from app_new.core.models.company import Part
    from app_new.contracts.models import Contract

    output = io.StringIO()
    writer = csv.writer(output, delimiter=';')
    writer.writerow(['Nature', 'Référence', 'Libellé', 'Date', 'Montant EUR', 'Statut'])
    for intervention in Intervention.query.filter(Intervention.is_deleted.is_(False)).all():
        writer.writerow(['Intervention', intervention.id, intervention.title,
                         intervention.completed_at.date().isoformat() if intervention.completed_at else '',
                         f'{intervention.cost or 0:.2f}', intervention.status])
    for contract in Contract.query.all():
        writer.writerow(['Contrat annuel', contract.contract_number or contract.id, contract.name,
                         contract.start_date.isoformat(), f'{contract.annual_amount or 0:.2f}', contract.status])
    for part in Part.query.all():
        writer.writerow(['Valeur du stock', part.reference or part.id, part.name, '',
                         f'{(part.quantity or 0) * (part.unit_price or 0):.2f}', f'{part.quantity or 0} {part.unit or ""}'])
    response = make_response('\ufeff' + output.getvalue())
    response.headers['Content-Type'] = 'text/csv; charset=utf-8'
    response.headers['Content-Disposition'] = 'attachment; filename=couts_gmao.csv'
    return response
