"""Helper de logging centralise pour les watchdogs GMAO."""
import os
import sys
import traceback
from datetime import datetime, timezone

# Insérer /app dans le path si besoin
if '/app' not in sys.path:
    sys.path.insert(0, '/app')


def log_to_db(watchdog_name, message, level='info'):
    """Écrit un log dans la base centralisee."""
    try:
        from app_new import create_app
        from app_new.extensions import db
        from app_new.core.models.maintenance import WatchdogLog
        
        app = create_app()
        with app.app_context():
            log = WatchdogLog(
                watchdog_name=watchdog_name,
                level=level,
                message=message
            )
            db.session.add(log)
            db.session.commit()
    except Exception:
        # Si la DB echoue, on ne bloque pas le watchdog
        pass


def log_watchdog(watchdog_name, message, level='info', also_print=True):
    """Logue un evenement watchdog (console + DB)."""
    timestamp = datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S')
    line = f"[{timestamp}] [{watchdog_name}] [{level.upper()}] {message}"
    if also_print:
        print(line)
    log_to_db(watchdog_name, message, level)


def log_exception(watchdog_name, exc, message=None):
    """Loggue une exception."""
    tb = traceback.format_exc()
    full = f"{message + ' ' if message else ''}{str(exc)}\n{tb}"
    log_watchdog(watchdog_name, full, level='error')
