"""Logs centralises des watchdogs."""
from flask import Blueprint, render_template, request, jsonify, flash, redirect, url_for
from flask_login import login_required
from datetime import datetime, timezone, timedelta
from app_new.core.models.settings import AppSettings
from sqlalchemy import text
from app_new.extensions import db
from app_new.core.models.maintenance import WatchdogLog
from app_new.core.system_security import system_admin_required

logs_bp = Blueprint('logs', __name__, url_prefix='/logs', template_folder='templates')


@logs_bp.route('/')
@login_required
def index():
    """Page de logs centralises."""
    page = request.args.get('page', 1, type=int)
    per_page = 100
    level = request.args.get('level', '')
    watchdog = request.args.get('watchdog', '')
    
    query = WatchdogLog.query
    if level:
        query = query.filter_by(level=level)
    if watchdog:
        query = query.filter_by(watchdog_name=watchdog)
    
    pagination = query.order_by(WatchdogLog.created_at.desc()).paginate(
        page=page, per_page=per_page, error_out=False
    )
    
    watchdogs = db.session.query(WatchdogLog.watchdog_name).distinct().order_by(WatchdogLog.watchdog_name).all()
    watchdogs = [w[0] for w in watchdogs]
    
    return render_template('logs/index.html',
                          pagination=pagination,
                          watchdogs=watchdogs,
                          filters={'level': level, 'watchdog': watchdog},
                          retention_days=int(AppSettings.get('watchdog_log_retention_days', '90')))


@logs_bp.route('/api/recent')
@login_required
def api_recent():
    """API JSON des logs recents."""
    limit = min(request.args.get('limit', 50, type=int), 500)
    level = request.args.get('level', '')
    watchdog = request.args.get('watchdog', '')
    
    query = WatchdogLog.query
    if level:
        query = query.filter_by(level=level)
    if watchdog:
        query = query.filter_by(watchdog_name=watchdog)
    
    logs = query.order_by(WatchdogLog.created_at.desc()).limit(limit).all()
    return jsonify([{
        'id': log.id,
        'watchdog_name': log.watchdog_name,
        'level': log.level,
        'message': log.message,
        'created_at': log.created_at.isoformat() if log.created_at else None
    } for log in logs])


@logs_bp.route('/clear', methods=['POST'])
@system_admin_required
def clear_watchdog_logs():
    """Vide integralement la table dediee aux journaux des watchdogs."""
    db.session.execute(text('TRUNCATE TABLE watchdog_logs'))
    db.session.commit()
    flash('Les journaux des watchdogs ont été vidés.', 'success')
    return redirect(url_for('logs.index'))


@logs_bp.route('/retention', methods=['POST'])
@system_admin_required
def apply_retention():
    days = max(1, min(request.form.get('days', type=int) or 90, 3650))
    cutoff = datetime.now(timezone.utc) - timedelta(days=days)
    deleted = WatchdogLog.query.filter(WatchdogLog.created_at < cutoff).delete(synchronize_session=False)
    db.session.commit()
    AppSettings.set('watchdog_log_retention_days', str(days), 'Durée de conservation des logs watchdog')
    flash(f'Rétention fixée à {days} jours ; {deleted} ancien(s) journal(aux) supprimé(s).', 'success')
    return redirect(url_for('logs.index'))
