import { createHash } from 'node:crypto';
import { PERCEPTION_REPORT_VIEW, type PerceptionReportContent } from '../../perception/report-content.js';
import { gameSyncPerceptionReportMessage } from '../../../../game-sync-protocol.js';
import type { GameSyncPerceptionReport } from '../../../../game-sync-protocol.js';
import type { CanonicalEvent } from '../../../../framework/events/index.js';
import type {
  ClawclawMailboxAdapterDescriptor,
  ClawclawMailboxDriver,
} from '../mailbox-plugin.js';

const GAME_SYNC_PERCEPTION_REPORT_BATCH_SIZE = 20;
const PERCEPTION_REPORT_UUID_NAMESPACE = Buffer.from(
  '3c45fc594dd54a59a22185085c1096d1',
  'hex',
);

export interface GameSyncPerceptionDescriptor {
  readonly perceptionId: string;
  readonly name: string;
}

export interface GameSyncPerceptionReportAdapterOptions {
  readonly send: (reports: readonly GameSyncPerceptionReport[]) => boolean;
  readonly descriptor: (perceiverId: string) => GameSyncPerceptionDescriptor | undefined;
  readonly producerPluginIds: readonly string[];
  readonly diagnostic?: (
    name: string,
    attributes?: Readonly<Record<string, unknown>>,
  ) => void;
}

function uuidForEvent(event: CanonicalEvent): string {
  const bytes = createHash('sha1')
    .update(PERCEPTION_REPORT_UUID_NAMESPACE)
    .update(event.sessionId)
    .update('\0')
    .update(event.eventId)
    .digest()
    .subarray(0, 16);
  bytes[6] = (bytes[6]! & 0x0f) | 0x50;
  bytes[8] = (bytes[8]! & 0x3f) | 0x80;
  const hex = bytes.toString('hex');
  return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
}

/** Best-effort reporting of newly committed perceptions, independent of Agent delivery. */
export class GameSyncPerceptionReportAdapter implements ClawclawMailboxDriver {
  readonly adapter: ClawclawMailboxAdapterDescriptor = {
    id: 'clawclaw.mailbox.adapter.game-sync-perception-report',
    acknowledgement: 'none',
  };

  private stopped = false;
  private sessionId?: string;
  private readonly reported = new Set<string>();

  constructor(private readonly options: GameSyncPerceptionReportAdapterOptions) {}

  /** Mailbox calls this after the producing epoch's Ready boundary is committed. */
  observeEvents(events: readonly CanonicalEvent[]): void {
    if (this.stopped) return;
    let skipped = 0;
    const reports: GameSyncPerceptionReport[] = [];
    for (const event of events) {
      if (this.sessionId !== event.sessionId) {
        this.sessionId = event.sessionId;
        this.reported.clear();
      }
      if (this.reported.has(event.eventId)) continue;
      if (
        !event.producerPluginId || !this.options.producerPluginIds.includes(event.producerPluginId)
        || event.deliveryClass === 'internal_only'
      ) continue;
      const content = event.notificationContent?.views?.[PERCEPTION_REPORT_VIEW] as PerceptionReportContent | undefined;
      const descriptor = content && this.options.descriptor(content.perceiver_id);
      if (!content || !descriptor || !descriptor.name.trim() || !content.output) {
        skipped += 1;
        continue;
      }
      let report: GameSyncPerceptionReport;
      try {
        report = gameSyncPerceptionReportMessage([{
          ...content, id: uuidForEvent(event), name: descriptor.name.trim(),
        }]).data.perceptions[0]!;
      } catch { skipped += 1; continue; }
      this.reported.add(event.eventId);
      reports.push(report);
    }
    if (skipped > 0) {
      this.options.diagnostic?.('runtime.mailbox.perception_report_skipped', {
        event_count: skipped,
        error_code: 'PERCEPTION_REPORT_FIELDS_MISSING',
      });
    }
    for (let index = 0; index < reports.length; index += GAME_SYNC_PERCEPTION_REPORT_BATCH_SIZE) {
      const batch = reports.slice(index, index + GAME_SYNC_PERCEPTION_REPORT_BATCH_SIZE);
      if (!this.options.send(batch)) {
        this.options.diagnostic?.('runtime.mailbox.perception_report_dropped', {
          event_count: batch.length,
          error_code: 'GAME_SYNC_NOT_CONNECTED',
        });
      }
    }
  }

  async flush(): Promise<void> {}

  async stop(): Promise<void> {
    this.stopped = true;
  }
}
