<?php

declare(strict_types=1);

namespace KimaAI\Ai\Providers\OpenAI\Endpoint;

use KimaAI\Ai\Providers\OpenAI\OpenAiClient;


final class Chat {
  /**
   * OpenAI client wrapper.
   *
   * @var OpenAiClient
   */
  private OpenAiClient $client;

  public function __construct(OpenAiClient $client) {
    $this->client = $client;
  }

  public function create(array $params): array {
    if ($this->client->isTestMode()) {
      // If in test mode, return a mock response
      return $this->mockCreate($params);
    }
    return $this->client->request('POST', '/chat/completions', $params);
  }

  /**
   * Return a mock chat completion response.
   *
   * @param array $params Requested chat payload.
   * @return array
   */
  public function mockCreate(array $params): array {
    // Mock response for testing purposes
    $mock_response = [
      'id' => 'chatcmpl-BtJXzj9IlSQVMm0J8KEQ5WNCMS6Ft',
      'object' => 'chat.completion',
      'created' => 1752522879,
      'model' => isset($params['model']) ? (string) $params['model'] : 'gpt-4o-mini-2024-07-18',

      'choices' => [
        [
          'index' => 0,
          'message' => [
            'role' => 'assistant',
            'content' => 'The "TEST API" is on, this is a mock response.',
            'refusal' => null,
            'annotations' => [],
          ],
          'logprobs' => null,
          'finish_reason' => 'stop',
        ],
      ],

      'usage' => [
        'prompt_tokens' => 8,
        'completion_tokens' => 9,
        'total_tokens' => 17,
        'prompt_tokens_details' => [
          'cached_tokens' => 0,
          'audio_tokens' => 0,
        ],
        'completion_tokens_details' => [
          'reasoning_tokens' => 0,
          'audio_tokens' => 0,
          'accepted_prediction_tokens' => 0,
          'rejected_prediction_tokens' => 0,
        ],
      ],

      'service_tier' => 'default',
      'system_fingerprint' => null,
    ];

    // Simulate a delay for realism
    usleep(100000); // 100 milliseconds
    return $mock_response;
  }
}
