<?php

declare(strict_types=1);

namespace Drupal\flowdrop\DTO\Reason;

/**
 * The outcome of one reasoning step: what the model wants to do next.
 *
 * Either a set of `toolCalls` (the model wants to call tools — dispatch them to
 * a tool-invoke node) or a final `text` answer. Provider-neutral: a
 * ChatReasonerInterface implementation builds it from its backend's response.
 *
 * @api
 */
final class ReasonResult {

  /**
   * Constructs a ReasonResult.
   *
   * @param string $text
   *   The assistant prose (a final answer, or commentary alongside tool calls).
   * @param array<int, array<string, mixed>> $toolCalls
   *   The calls the model requested, each {name, args, tool_call_id}. Empty
   *   when the model answered directly.
   */
  public function __construct(
    private readonly string $text,
    private readonly array $toolCalls = [],
  ) {}

  /**
   * The assistant prose.
   *
   * @return string
   *   A final answer, or commentary alongside tool calls.
   */
  public function getText(): string {
    return $this->text;
  }

  /**
   * The tool calls the model requested.
   *
   * @return array<int, array<string, mixed>>
   *   Each call is {name, args, tool_call_id}; empty when answered directly.
   */
  public function getToolCalls(): array {
    return $this->toolCalls;
  }

  /**
   * Whether the model wants to call at least one tool.
   *
   * @return bool
   *   TRUE if there are tool calls to dispatch — branch the loop on this.
   */
  public function hasToolCalls(): bool {
    return $this->toolCalls !== [];
  }

  /**
   * The assistant turn as a conversation-buffer message.
   *
   * Append this to the conversation buffer to persist the turn (including any
   * tool calls) so the next iteration replays a well-formed history.
   *
   * @return array<string, mixed>
   *   The {role, content, tool_calls} assistant message.
   */
  public function getAssistantMessage(): array {
    return [
      'role' => 'assistant',
      'content' => $this->text,
      'tool_calls' => $this->toolCalls,
    ];
  }

}
