import { randomUUID } from 'node:crypto';
import { appendFileSync, mkdirSync } from 'node:fs';
import { dirname } from 'node:path';

import type { MACPEvent } from './types.js';

export function nowISO(): string {
  return new Date().toISOString();
}

export function appendEvent(eventsPath: string, event: MACPEvent): void {
  mkdirSync(dirname(eventsPath), { recursive: true });
  appendFileSync(eventsPath, JSON.stringify(event) + '\n', 'utf-8');
}

export function emitEvent(
  eventsPath: string,
  eventType: string,
  taskId: string,
  status: string,
  source: string,
  message: string,
  metadata?: Record<string, unknown>,
): void {
  appendEvent(eventsPath, {
    event_id: randomUUID(),
    event_type: eventType,
    task_id: taskId,
    status,
    timestamp: nowISO(),
    source,
    message,
    metadata: metadata ?? {},
  });
}
