<?php

declare(strict_types=1);

namespace OpenAI\Responses\Images\Streaming;

use OpenAI\Contracts\ResponseContract;
use OpenAI\Contracts\ResponseHasMetaInformationContract;
use OpenAI\Responses\Concerns\ArrayAccessible;
use OpenAI\Responses\Concerns\HasMetaInformation;
use OpenAI\Responses\Images\ImageResponseUsage;
use OpenAI\Responses\Meta\MetaInformation;
use OpenAI\Testing\Responses\Concerns\Fakeable;

/**
 * @phpstan-type ImageGenerationCompletedType array{type: string, b64_json: string, created_at: int, size: string, quality: string, background: string, output_format: string, usage?: array{total_tokens: int, input_tokens: int|null, output_tokens: int|null, input_tokens_details: array{text_tokens: int, image_tokens: int}|null}}
 *
 * @implements ResponseContract<ImageGenerationCompletedType>
 */
final class ImageGenerationCompleted implements ResponseContract, ResponseHasMetaInformationContract
{
    /**
     * @use ArrayAccessible<ImageGenerationCompletedType>
     */
    use ArrayAccessible;

    use Fakeable;
    use HasMetaInformation;

    private function __construct(
        public readonly string $type,
        public readonly string $b64Json,
        public readonly int $createdAt,
        public readonly string $size,
        public readonly string $quality,
        public readonly string $background,
        public readonly string $outputFormat,
        private readonly MetaInformation $meta,
        public readonly ?ImageResponseUsage $usage = null,
    ) {}

    /**
     * @param  ImageGenerationCompletedType  $attributes
     */
    public static function from(array $attributes, MetaInformation $meta): self
    {
        return new self(
            type: $attributes['type'],
            b64Json: $attributes['b64_json'],
            createdAt: $attributes['created_at'],
            size: $attributes['size'],
            quality: $attributes['quality'],
            background: $attributes['background'],
            outputFormat: $attributes['output_format'],
            meta: $meta,
            usage: isset($attributes['usage']) ? ImageResponseUsage::from($attributes['usage']) : null,
        );
    }

    /**
     * {@inheritDoc}
     */
    public function toArray(): array
    {
        $result = [
            'type' => $this->type,
            'b64_json' => $this->b64Json,
            'created_at' => $this->createdAt,
            'size' => $this->size,
            'quality' => $this->quality,
            'background' => $this->background,
            'output_format' => $this->outputFormat,
        ];

        if ($this->usage !== null) {
            $result['usage'] = $this->usage->toArray();
        }

        return $result;
    }
}
