<?php

declare(strict_types=1);

namespace KimaAI\Ai\Providers\DTO;

final class ChatRequest {
  public function __construct(
    public string $model,
    public array $input = [],
    public array $messages = [],
    public ?float $temperature = null,
    public ?int $max_output_tokens = null,
    public array $tools = [],
    public array $provider_options = []
  ) {
  }

  public static function fromArray(array $payload): self {
    return new self(
      (string) ($payload['model'] ?? ''),
      is_array($payload['input'] ?? null) ? $payload['input'] : [],
      is_array($payload['messages'] ?? null) ? $payload['messages'] : [],
      isset($payload['temperature']) ? (float) $payload['temperature'] : null,
      isset($payload['max_output_tokens']) ? (int) $payload['max_output_tokens'] : null,
      is_array($payload['tools'] ?? null) ? $payload['tools'] : [],
      $payload
    );
  }

  public function toArray(): array {
    $payload = $this->provider_options;

    if ($this->model !== '') {
      $payload['model'] = $this->model;
    }
    if ($this->input !== []) {
      $payload['input'] = $this->input;
    }
    if ($this->messages !== []) {
      $payload['messages'] = $this->messages;
    }
    if ($this->temperature !== null) {
      $payload['temperature'] = $this->temperature;
    }
    if ($this->max_output_tokens !== null) {
      $payload['max_output_tokens'] = $this->max_output_tokens;
    }
    if ($this->tools !== []) {
      $payload['tools'] = $this->tools;
    }

    return $payload;
  }
}
