"""Service logs QuickWin — journalisation des actions et erreurs par campagne"""
from sqlalchemy import text


def log_entry(db, run_id, step, level, message, detail=None,
              entry_id=None, hostname=None, created_by=None):
    """Ajoute une ligne de log pour un run QuickWin.
    level: info, warn, error, success"""
    db.execute(text("""
        INSERT INTO quickwin_logs (run_id, entry_id, hostname, step, level, message, detail, created_by)
        VALUES (:rid, :eid, :host, :step, :lvl, :msg, :det, :by)
    """), {
        "rid": run_id, "eid": entry_id, "host": hostname,
        "step": step, "lvl": level, "msg": message,
        "det": detail, "by": created_by,
    })


def log_info(db, run_id, step, message, **kwargs):
    log_entry(db, run_id, step, "info", message, **kwargs)


def log_warn(db, run_id, step, message, **kwargs):
    log_entry(db, run_id, step, "warn", message, **kwargs)


def log_error(db, run_id, step, message, **kwargs):
    log_entry(db, run_id, step, "error", message, **kwargs)


def log_success(db, run_id, step, message, **kwargs):
    log_entry(db, run_id, step, "success", message, **kwargs)


def get_logs(db, run_id, level=None, step=None, hostname=None, limit=500):
    """Recupere les logs d'un run avec filtres optionnels."""
    where = ["run_id = :rid"]
    params = {"rid": run_id}
    if level:
        where.append("level = :lvl")
        params["lvl"] = level
    if step:
        where.append("step = :step")
        params["step"] = step
    if hostname:
        where.append("hostname ILIKE :host")
        params["host"] = f"%{hostname}%"
    params["lim"] = limit
    return db.execute(text(f"""
        SELECT * FROM quickwin_logs
        WHERE {' AND '.join(where)}
        ORDER BY created_at DESC
        LIMIT :lim
    """), params).fetchall()


def get_log_stats(db, run_id):
    """Compteurs par level pour un run."""
    return db.execute(text("""
        SELECT level, COUNT(*) as cnt
        FROM quickwin_logs WHERE run_id = :rid
        GROUP BY level ORDER BY level
    """), {"rid": run_id}).fetchall()


def clear_logs(db, run_id, step=None):
    """Supprime les logs d'un run (optionnel: seulement une etape)."""
    if step:
        db.execute(text("DELETE FROM quickwin_logs WHERE run_id = :rid AND step = :step"),
                   {"rid": run_id, "step": step})
    else:
        db.execute(text("DELETE FROM quickwin_logs WHERE run_id = :rid"), {"rid": run_id})
    db.commit()
