"""Audit logging for auth and user actions."""
from __future__ import annotations
import sqlite3
from datetime import datetime, timezone, timedelta
from pathlib import Path
from .db import _connect


def log_event(
    db_path: Path, *,
    user_id: str | None = None,
    action: str,
    detail: str | None = None,
    ip_address: str | None = None,
) -> None:
    """Record an audit event in server.db."""
    conn = _connect(db_path)
    try:
        conn.execute(
            "INSERT INTO audit_log (user_id, action, detail, ip_address) VALUES (?, ?, ?, ?)",
            (user_id, action, detail, ip_address),
        )
        conn.commit()
    finally:
        conn.close()


def get_recent_events(db_path: Path, *, limit: int = 100) -> list[dict]:
    """Get recent audit events, newest first."""
    conn = _connect(db_path)
    try:
        rows = conn.execute(
            "SELECT timestamp, user_id, action, detail, ip_address FROM audit_log ORDER BY id DESC LIMIT ?",
            (limit,),
        ).fetchall()
    finally:
        conn.close()
    return [
        {"timestamp": r[0], "user_id": r[1], "action": r[2], "detail": r[3], "ip_address": r[4]}
        for r in rows
    ]


def cleanup_old_events(db_path: Path, *, retention_days: int) -> int:
    """Delete audit events older than retention_days. Returns count deleted. 0 = keep forever."""
    if retention_days <= 0:
        return 0
    cutoff = (datetime.now(timezone.utc) - timedelta(days=retention_days)).isoformat()
    conn = _connect(db_path)
    try:
        cursor = conn.execute("DELETE FROM audit_log WHERE timestamp < ?", (cutoff,))
        deleted = cursor.rowcount
        conn.commit()
    finally:
        conn.close()
    return deleted
