"""Audit logging — logs every API interaction to v3q_config.audit_log."""

from __future__ import annotations

import json
from typing import Any

from database.connection_manager import ConnectionManager


class AuditLog:
    def __init__(self, cm: ConnectionManager) -> None:
        self._cm = cm

    async def log(
        self,
        event_type: str,
        direction: str,
        payload_hash: str,
        payload_size: int,
        contains_data: bool = False,
        metadata: dict[str, Any] | None = None,
    ) -> None:
        """Write an audit log entry."""
        await self._cm.execute_write("""
            INSERT INTO v3q_config.audit_log
                (event_type, direction, payload_hash, payload_size, contains_data, metadata)
            VALUES (:event_type, :direction, :payload_hash, :payload_size, :contains_data, :metadata)
        """, {
            "event_type": event_type,
            "direction": direction,
            "payload_hash": payload_hash,
            "payload_size": payload_size,
            "contains_data": contains_data,
            "metadata": json.dumps(metadata) if metadata else None,
        })

    async def list_recent(self, limit: int = 50) -> list[dict]:
        return await self._cm.execute(
            "SELECT * FROM v3q_config.audit_log ORDER BY created_at DESC LIMIT :limit",
            {"limit": limit},
        )

    async def count_blocked(self) -> int:
        row = await self._cm.fetch_one(
            "SELECT COUNT(*) as cnt FROM v3q_config.audit_log WHERE contains_data = true"
        )
        return row["cnt"] if row else 0

    async def get_stats(self) -> dict:
        """Get audit statistics."""
        total = await self._cm.fetch_one(
            "SELECT COUNT(*) as cnt FROM v3q_config.audit_log"
        )
        blocked = await self._cm.fetch_one(
            "SELECT COUNT(*) as cnt FROM v3q_config.audit_log WHERE contains_data = true"
        )
        outbound = await self._cm.fetch_one(
            "SELECT COUNT(*) as cnt FROM v3q_config.audit_log WHERE direction = 'outbound'"
        )
        return {
            "total_events": total["cnt"] if total else 0,
            "blocked_events": blocked["cnt"] if blocked else 0,
            "outbound_calls": outbound["cnt"] if outbound else 0,
        }
