from __future__ import annotations

import json
import uuid
from datetime import datetime, timezone
from sqlite3 import Connection
from typing import Any


def utc_now() -> str:
    return datetime.now(timezone.utc).isoformat()


def record_audit_event(
    conn: Connection,
    *,
    source: str,
    action: str,
    entity_type: str,
    entity_id: str,
    old_values: dict[str, Any] | None = None,
    new_values: dict[str, Any] | None = None,
    user_text_note: str | None = None,
    confirmed: bool = True,
    created_by: str = "system",
) -> str:
    audit_id = str(uuid.uuid4())
    now = utc_now()
    conn.execute(
        """
        INSERT INTO audit_log(
            audit_id, timestamp, source, action, entity_type, entity_id,
            old_values_json, new_values_json, user_text_note, confirmed,
            confirmation_timestamp, created_by, created_at
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        """,
        (
            audit_id,
            now,
            source,
            action,
            entity_type,
            entity_id,
            json.dumps(old_values or {}, sort_keys=True),
            json.dumps(new_values or {}, sort_keys=True),
            user_text_note,
            1 if confirmed else 0,
            now if confirmed else None,
            created_by,
            now,
        ),
    )
    return audit_id
