"""Shared audit trail utilities.

Extracted from isms_routes.py for reuse across evidence, control,
and assertion routes.
"""

import hashlib
import uuid
from datetime import datetime

from sqlalchemy.orm import Session

from ..db.models import AuditTrailDB


def generate_id() -> str:
    """Generate a UUID string."""
    return str(uuid.uuid4())


def create_signature(data: str) -> str:
    """Create SHA-256 signature."""
    return hashlib.sha256(data.encode()).hexdigest()


def log_audit_trail(
    db: Session,
    entity_type: str,
    entity_id: str,
    entity_name: str,
    action: str,
    performed_by: str,
    field_changed: str = None,
    old_value: str = None,
    new_value: str = None,
    change_summary: str = None,
):
    """Log an entry to the audit trail."""
    trail = AuditTrailDB(
        id=generate_id(),
        entity_type=entity_type,
        entity_id=entity_id,
        entity_name=entity_name,
        action=action,
        field_changed=field_changed,
        old_value=old_value,
        new_value=new_value,
        change_summary=change_summary,
        performed_by=performed_by,
        performed_at=datetime.utcnow(),
        checksum=create_signature(f"{entity_type}|{entity_id}|{action}|{performed_by}"),
    )
    db.add(trail)
