"""
Klausur-Service EH Service

Functions for audit logging and EH-related utilities.
"""

import uuid
from datetime import datetime, timezone
from typing import Dict, Optional

from models.grading import AuditLogEntry
from models.eh import EHAuditLogEntry

# Import storage - will be initialized by main.py
# These imports need to reference the actual storage module
import storage


def log_audit(
    user_id: str,
    action: str,
    entity_type: str,
    entity_id: str,
    field: str = None,
    old_value: str = None,
    new_value: str = None,
    details: Dict = None
) -> AuditLogEntry:
    """
    Add an entry to the general audit log.

    Args:
        user_id: ID of the user performing the action
        action: Type of action (score_update, gutachten_update, etc.)
        entity_type: Type of entity (klausur, student)
        entity_id: ID of the entity
        field: Optional field name that was changed
        old_value: Optional old value
        new_value: Optional new value
        details: Optional additional details

    Returns:
        The created AuditLogEntry
    """
    entry = AuditLogEntry(
        id=str(uuid.uuid4()),
        timestamp=datetime.now(timezone.utc),
        user_id=user_id,
        action=action,
        entity_type=entity_type,
        entity_id=entity_id,
        field=field,
        old_value=old_value,
        new_value=new_value,
        details=details
    )
    storage.audit_log_db.append(entry)
    return entry


def log_eh_audit(
    tenant_id: str,
    user_id: str,
    action: str,
    eh_id: str = None,
    details: Dict = None,
    ip_address: str = None,
    user_agent: str = None
) -> EHAuditLogEntry:
    """
    Add an entry to the EH audit log.

    Args:
        tenant_id: Tenant ID
        user_id: ID of the user performing the action
        action: Type of action (upload, index, rag_query, etc.)
        eh_id: Optional EH ID
        details: Optional additional details
        ip_address: Optional client IP address
        user_agent: Optional client user agent

    Returns:
        The created EHAuditLogEntry
    """
    entry = EHAuditLogEntry(
        id=str(uuid.uuid4()),
        eh_id=eh_id,
        tenant_id=tenant_id,
        user_id=user_id,
        action=action,
        details=details,
        ip_address=ip_address,
        user_agent=user_agent,
        created_at=datetime.now(timezone.utc)
    )
    storage.eh_audit_db.append(entry)
    return entry
