<?php

declare(strict_types=1);

namespace KimaAI\Ai\Providers\OpenAI\Endpoint;

use KimaAI\Ai\Providers\OpenAI\OpenAiClient;


/**
 * Wrapper for the /v1/responses family of routes
 *
 * @see https://platform.openai.com/docs/api-reference/responses
 */
final class Responses {
  public function __construct(private OpenAiClient $client) {
  }

  /**
   * Create a new response-session (stateful)
   *
   * @param array $params
   * @param bool $stream
   * @param callable|null $on_chunk function(string $chunk): void
   * @return array
   */
  public function create(array $params, bool $stream = false, ?callable $on_chunk = null): array {
    if ($this->client->isTestMode()) {
      return $this->mockCreate($params);
    }
    return $this->client->request('POST', '/responses', $params, $stream, [], $on_chunk);
  }

  /**
   * Continue a previous response by creating a new response linked to it.
   * This is the supported way to resume after tool outputs.
   */
  public function continueResponse(string $previous_response_id, array $params, bool $stream = false, ?callable $on_chunk = null): array {
    $params['previous_response_id'] = $previous_response_id;
    return $this->create($params, $stream, $on_chunk);
  }

  /**
   * Retrieve a single response object
   */
  public function retrieve(string $response_id): array {
    return $this->client->request('GET', "/responses/{$response_id}");
  }

  /**
   * Append additional user / system content
   *
   * @param string $previous_response_id
   * @param array $params
   * @param bool $stream
   * @param callable|null $on_chunk function(string $chunk): void
   * @return array
   */
  public function addContent(string $previous_response_id, array $params, bool $stream = false, ?callable $on_chunk = null): array {
    return $this->continueResponse($previous_response_id, $params, $stream, $on_chunk);
  }

  /**
   * Delete & free storage (30-day default retention)
   */
  public function delete(string $response_id): array {
    return $this->client->request('DELETE', "/responses/{$response_id}");
  }

  /**
   * List responses (pagination params mirror Assistants)
   */
  public function list(array $query = []): array {
    return $this->client->request('GET', '/responses', $query);
  }

  /**
   * Return a mock Responses API payload.
   *
   * @param array $params Requested response payload.
   * @return array
   */
  public function mockCreate(array $params): array {
    // Mock response for testing purposes
    $mock_response = [
      'id' => 'resp_6875622e1eb4819e89fce0a560b6ed91095430b462227bd3',
      'object' => 'response',
      'created_at' => 1752523310,
      'status' => 'completed',
      'background' => null,
      'error' => null,
      'incomplete_details' => null,
      'instructions' => null,
      'max_output_tokens' => null,
      'max_tool_calls' => null,
      'model' => isset($params['model']) ? (string) $params['model'] : 'gpt-4o-mini-2024-07-18',

      'output' => [
        [
          'id' => 'msg_6875622e65f0819eb7d66fac8736833c095430b462227bd3',
          'type' => 'message',
          'status' => 'completed',
          'content' => [
            [
              'type' => 'output_text',
              'annotations' => [],
              'logprobs' => [],
              'text' => 'The "TEST API" is on, this is a mock response.',
            ],
          ],
          'role' => 'assistant',
        ],
      ],

      'parallel_tool_calls' => 1,
      'previous_response_id' => null,

      'reasoning' => [
        'effort' => null,
        'summary' => null,
      ],

      'service_tier' => 'default',
      'store' => 1,
      'temperature' => 1,

      'text' => [
        'format' => [
          'type' => 'text',
        ],
      ],

      'tool_choice' => 'auto',
      'tools' => [],

      'top_logprobs' => 0,
      'top_p' => 1,
      'truncation' => 'disabled',

      'usage' => [
        'input_tokens' => 8,
        'input_tokens_details' => [
          'cached_tokens' => 0,
        ],
        'output_tokens' => 11,
        'output_tokens_details' => [
          'reasoning_tokens' => 0,
        ],
        'total_tokens' => 19,
      ],

      'user' => null,
      'metadata' => [],
    ];

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