<?php

namespace Datalumo\PhpSdk\DataObjects;

class StreamEvent
{
    public function __construct(
        public readonly string $type,
        public readonly ?string $data = null,
        public readonly ?array $raw = null,
    ) {}

    public static function fromArray(array $data): self
    {
        return new self(
            type: $data['type'] ?? 'unknown',
            data: $data['delta'] ?? $data['message'] ?? null,
            raw: $data,
        );
    }

    public function isTextDelta(): bool
    {
        return $this->type === 'text_delta';
    }

    public function isCitation(): bool
    {
        return $this->type === 'citation';
    }

    public function isStreamEnd(): bool
    {
        return $this->type === 'stream_end';
    }

    public function isError(): bool
    {
        return str_contains($this->type, 'error');
    }

    /** @return array{title: string, url: string}|null */
    public function citation(): ?array
    {
        return $this->raw['citation'] ?? null;
    }
}
