# standard
import json
import datetime
import pathlib

# third party
# custom
from sunwaee.config import get_caller, get_workspaces_base_dir
from sunwaee.core.logger import get_logger
from sunwaee.modules.logs.model import LogEntry

_log = get_logger("core.audit")


def _log_path(workspace: str) -> pathlib.Path:
    """Returns the log path for new log entries."""

    now = datetime.datetime.now(datetime.timezone.utc)
    base = get_workspaces_base_dir()
    return (
        base
        / workspace
        / "logs"
        / str(now.year)
        / f"{now.month:02d}"
        / f"{now.day:02d}"
        / "logs.jsonl"
    )


def append_log(
    workspace: str,
    module: str,
    operation: str,
    ok: bool = True,
    item_id: str | None = None,
    item_title: str | None = None,
    args: dict | None = None,
) -> None:
    """Append an audit log entry for the given workspace. Silently ignores I/O errors."""

    try:
        path = _log_path(workspace)
        path.parent.mkdir(parents=True, exist_ok=True)
        entry = LogEntry(
            timestamp=datetime.datetime.now(datetime.timezone.utc).isoformat(),
            caller=get_caller().value,
            workspace=workspace,
            module=module,
            operation=operation,
            ok=ok,
            item_id=item_id,
            item_title=item_title,
            args=args or None,
        )
        with open(path, "a") as f:
            f.write(json.dumps(entry.to_dict()) + "\n")
    except Exception as exc:  # pragma: no cover
        _log.warning("Failed to write audit log: %s", exc)
