<?php

declare(strict_types=1);

namespace KimaAI\Ai\Providers\Support;

final class SseParser {
  /**
   * Buffered partial SSE frame data.
   *
   * @var string
   */
  private string $buffer = '';

  /**
   * Parse complete SSE frames from the current buffer.
   *
   * @return list<array{data:string,event:string|null,raw:string}>
   */
  public function push(string $chunk): array {
    $this->buffer .= str_replace("\r\n", "\n", $chunk);
    $frames = [];

    // phpcs:ignore
    while (($pos = strpos($this->buffer, "\n\n")) !== false) {
      $raw = substr($this->buffer, 0, $pos);
      $this->buffer = substr($this->buffer, $pos + 2);

      $data = [];
      $event = null;
      foreach (preg_split("/\n/", $raw) ?: [] as $line) {
        $line = trim($line);
        if ($line === '' || str_starts_with($line, ':')) {
          continue;
        }
        if (str_starts_with($line, 'event:')) {
          $event = ltrim(substr($line, 6));
          continue;
        }
        if (str_starts_with($line, 'data:')) {
          $data[] = ltrim(substr($line, 5));
        }
      }

      if ($data !== []) {
        $frames[] = [
          'data' => implode("\n", $data),
          'event' => $event,
          'raw' => $raw,
        ];
      }
    }

    return $frames;
  }
}
