<?php
declare(strict_types=1);

namespace KimaAI\Ai\Providers\Ollama\Endpoint;

use KimaAI\Ai\Providers\Ollama\OllamaClient;
use RuntimeException;


/**
 * Ollama-compatible wrapper for /v1/responses.
 *
 * Important:
 * Ollama supports only the non-stateful flavor of the OpenAI Responses API.
 * So previous_response_id / conversation-style continuation must not be used.
 */
final class Responses {
  public function __construct(private OllamaClient $client) {
  }

  /**
   * Create a non-stateful response.
   *
   * @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);
    }

    // Ollama does not support stateful response continuation.
    unset($params['previous_response_id'], $params['conversation']);

    return $this->client->request('POST', '/responses', $params, $stream, [], $on_chunk);
  }

  /**
   * Not supported by Ollama's OpenAI-compatible Responses API.
   *
   * @throws RuntimeException Always, because Ollama does not support stateful continuation.
   */
  public function continueResponse(): array {
    throw new RuntimeException('Ollama /v1/responses does not support stateful continuation via previous_response_id.');
  }

  /**
   * Alias kept for API symmetry, but unsupported for Ollama.
   *
   * @throws RuntimeException Always, because Ollama does not support stateful continuation.
   */
  public function addContent(): array {
    throw new RuntimeException('Ollama /v1/responses does not support addContent/stateful continuation.');
  }

  /**
   * Not documented as supported on Ollama's OpenAI-compatible Responses API.
   *
   * @throws RuntimeException Always, because retrieve is unsupported.
   */
  public function retrieve(string $response_id): array {
    throw new RuntimeException(
      sprintf(
        'Ollama /v1/responses retrieve is not supported by this provider wrapper for response "%s".',
        sanitize_text_field($response_id)
      )
    );
  }

  /**
   * Not documented as supported on Ollama's OpenAI-compatible Responses API.
   *
   * @throws RuntimeException Always, because delete is unsupported.
   */
  public function delete(string $response_id): array {
    throw new RuntimeException(
      sprintf(
        'Ollama /v1/responses delete is not supported by this provider wrapper for response "%s".',
        sanitize_text_field($response_id)
      )
    );
  }

  /**
   * Not documented as supported on Ollama's OpenAI-compatible Responses API.
   *
   * @throws RuntimeException Always, because list is unsupported.
   */
  public function list(array $query = []): array {
    $suffix = $query === [] ? '' : ' Query parameters are not supported.';
    throw new RuntimeException('Ollama /v1/responses list is not supported by this provider wrapper.' . $suffix);
  }

  public function mockCreate(array $params): array {
    $mock_response = [
      'id' => 'resp_ollama_mock_1',
      'object' => 'response',
      'created_at' => time(),
      'status' => 'completed',
      'error' => null,
      'model' => $params['model'] ?? 'llama3.2',
      'output' => [
        [
          'id' => 'msg_ollama_mock_1',
          'type' => 'message',
          'status' => 'completed',
          'content' => [
            [
              'type' => 'output_text',
              'annotations' => [],
              'text' => 'The "TEST API" is on, this is a mock Ollama response.',
            ],
          ],
          'role' => 'assistant',
        ],
      ],
      'usage' => [
        'input_tokens' => 8,
        'output_tokens' => 11,
        'total_tokens' => 19,
      ],
    ];

    usleep(100000);

    return $mock_response;
  }
}
