from __future__ import annotations

import json
from pathlib import Path
from typing import Any
import uuid

from .format import ActionEvent, now_iso, to_json, normalize_tags


DEFAULT_LOG_DIR = Path.cwd() / ".areg"
DEFAULT_LOG_PATH = DEFAULT_LOG_DIR / "actions.jsonl"


def log_event(
    *,
    user_id: str,
    action_type: str,
    log_path: str | Path | None = None,
    event_id: str | None = None,
    tool: str | None = None,
    target: str | None = None,
    decision: str | None = None,
    status: str | None = None,
    reason: str | None = None,
    tags: list[str] | None = None,
    metadata: dict[str, Any] | None = None,
) -> str:
    path = Path(log_path) if log_path else DEFAULT_LOG_PATH
    path.parent.mkdir(parents=True, exist_ok=True)

    event = ActionEvent(
        id=event_id or str(uuid.uuid4()),
        ts=now_iso(),
        user_id=user_id,
        action_type=action_type,
        tool=tool,
        target=target,
        decision=decision,
        status=status,
        reason=reason,
        tags=normalize_tags(tags),
        metadata=metadata or {},
    )

    with path.open("a") as f:
        f.write(json.dumps(to_json(event), ensure_ascii=False) + "\n")

    return event.id
