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

from sqlalchemy.orm import Session as OrmSession

from app.logging.models import ActivityLog


class ActivityLogger:
    def __init__(self, db: OrmSession) -> None:
        self._db = db

    def log(
        self,
        *,
        actor_id: str,
        action: str,
        resource_type: str,
        resource_id: Optional[str] = None,
        project_id: Optional[str] = None,
        detail: Optional[dict] = None,
        ip_address: Optional[str] = None,
    ) -> None:
        try:
            entry = ActivityLog(
                id=str(uuid.uuid4()),
                actor_id=actor_id,
                action=action,
                resource_type=resource_type,
                resource_id=resource_id,
                project_id=project_id,
                detail_json=json.dumps(detail or {}, ensure_ascii=False),
                ip_address=ip_address,
                created_at=datetime.now(timezone.utc).isoformat(),
            )
            self._db.add(entry)
            self._db.commit()
        except Exception:
            # Logging failure must never block the main operation
            pass
