<?php
/**
 * Model Response Handler for DeepSeek AI Provider.
 *
 * Handles parsing of responses from the DeepSeek /models endpoint.
 *
 * @package Limb_Chatbot\Includes\AI_Providers\Deep_Seek\Endpoints\Model
 * @since   1.0.9
 */

namespace Limb_Chatbot\Includes\AI_Providers\Deep_Seek\Endpoints\Model;

use Limb_Chatbot\Includes\AI_Providers\Deep_Seek\Handlers\Response_Handler;
use Limb_Chatbot\Includes\Data_Objects\AI_Model;

/**
 * Class Response_Handler
 *
 * Parses and processes responses from the DeepSeek models listing endpoint.
 * Extracts model data from the API response format.
 *
 * @package Limb_Chatbot\Includes\AI_Providers\Deep_Seek\Endpoints\Model
 * @since   1.0.9
 */
class Model_Response_Handler extends Response_Handler {

	/**
	 * The AI model object parsed from the response.
	 *
	 * @var AI_Model|null
	 * @since 1.0.9
	 */
	protected ?AI_Model $model = null;

	/**
	 * Parse the API response and initialize the AI model.
	 *
	 * @since 1.0.9
	 */
	public function parse() {
		parent::parse();
		if ( ! $this->has_error() ) {
			$this->set_model( $this->model_factory() );
		}
	}

	/**
	 * Get the AI model object.
	 *
	 * @return AI_Model
	 * @since 1.0.9
	 */
	public function get_model(): AI_Model {
		return $this->model;
	}

	/**
	 * Set the AI model object.
	 *
	 * @param AI_Model $model The AI model to set.
	 *
	 * @since 1.0.9
	 */
	public function set_model( AI_Model $model ): void {
		$this->model = $model;
	}

	/**
	 * Create and return an AI model instance from the response body.
	 *
	 * @return AI_Model
	 * @since 1.0.9
	 */
	protected function model_factory(): AI_Model {
		$model = AI_Model::make();

		return $model;
	}

	/**
	 * Get the list of models from the API response.
	 *
	 * DeepSeek API returns models in the format:
	 * {
	 *   "object": "list",
	 *   "data": [
	 *     { "id": "deepseek-chat", "object": "model", "owned_by": "deepseek" },
	 *     { "id": "deepseek-reasoner", "object": "model", "owned_by": "deepseek" }
	 *   ]
	 * }
	 *
	 * @return array Array of model objects from the API response.
	 * @since  1.0.9
	 */
	public function get_models(): array {
		$body = $this->get_body();

		// Handle object response.
		if ( is_object( $body ) && isset( $body->data ) ) {
			return (array) $body->data;
		}

		// Handle array response.
		if ( is_array( $body ) && isset( $body['data'] ) ) {
			return $body['data'];
		}

		// Return empty array if no models found.
		return array();
	}

	/**
	 * Check whether the model has been deleted.
	 *
	 * @return bool Always false - DeepSeek doesn't support model deletion.
	 * @since 1.0.9
	 */
	public function is_deleted(): bool {
		return false;
	}
}

