#!/usr/bin/env python3
"""Append-only autonomy events for the shared Nightwatch ledger."""

from __future__ import annotations

import json
import socket
from datetime import datetime, timezone
from pathlib import Path
from typing import Any

from recoil.pipeline.tools.autonomy import constants

try:
    from recoil.pipeline.tools.nightwatch import utc_now_iso
except Exception:  # pragma: no cover - fallback for import/path failures.

    def utc_now_iso() -> str:
        return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")


def emit(
    event_type: str,
    *,
    run_id: str | None = None,
    issue_id: str | None = None,
    night_id: str | None = None,
    ledger: str | Path | None = None,
    **fields: Any,
) -> dict[str, Any]:
    """Append one namespaced autonomy event and return the emitted envelope."""
    if event_type not in constants.EVENT_TYPES:
        raise ValueError(f"unknown autonomy event type: {event_type}")

    event = {
        "schema": "autonomy.v1",
        "ts": utc_now_iso(),
        "event": f"autonomy.{event_type}",
        "run_id": run_id,
        "issue_id": issue_id,
        "night_id": night_id,
        "host": socket.gethostname(),
        **fields,
    }

    ledger_path = Path(ledger) if ledger is not None else constants.EVENTS_LEDGER
    ledger_path.parent.mkdir(parents=True, exist_ok=True)
    with ledger_path.open("a", encoding="utf-8") as handle:
        handle.write(json.dumps(event, sort_keys=True, separators=(",", ":")) + "\n")

    return event
