<?php
if (!defined('ABSPATH')) exit;

class click_n_chat_ai_provider {

	private $settings;

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

	public function reply($message) {

		switch ($this->settings->ai_provider) {

			case 'claude':
				return $this->claude($message);

			case 'gemini':
				return $this->gemini($message);

			case 'huggingface':
				return $this->huggingface($message);

			case 'cohere':
				return $this->cohere($message);

			case 'deepseek':
				return $this->deepseek($message);

			case 'openai':
			default:
				return $this->openai($message);
		}
	}

	/* ================= OPENAI ================= */
	private function openai($message) {

		$url = 'https://api.openai.com/v1/chat/completions';

		$data = [
			'model' => $this->settings->ai_models,
			'messages' => [
				['role' => 'system', 'content' => $this->settings->ai_instructions],
				['role' => 'user', 'content' => $message]
			],
			'max_tokens' => (int)$this->settings->max_token,
			'temperature' => (float)$this->settings->temperature,
		];

		return $this->post($url, [
			'Authorization' => 'Bearer ' . $this->settings->openai_api_key
		], $data, 'openai');
	}

	/* ================= CLAUDE ================= */
	private function claude($message) {

		$url = 'https://api.anthropic.com/v1/messages';

		$data = [
			'model'      => $this->settings->ai_models,
			'max_tokens' => (int)$this->settings->max_token,
			'messages'   => [
				['role' => 'user', 'content' => $message]
			],
		];

		// Pass ai_instructions as the top-level system prompt (Claude API format)
		if ( ! empty( $this->settings->ai_instructions ) ) {
			$data['system'] = $this->settings->ai_instructions;
		}

		return $this->post($url, [
			'x-api-key'         => $this->settings->claude_api_key,
			'anthropic-version' => '2023-06-01',
		], $data, 'claude');
	}

	/* ================= GEMINI ================= */
	private function gemini($message) {

		$url = 'https://generativelanguage.googleapis.com/v1beta/models/' .
			$this->settings->ai_models . ':generateContent?key=' .
			$this->settings->gemini_api_key;

		$data = [
			'contents' => [[
				'parts' => [['text' => $message]]
			]]
		];

		return $this->post($url, [], $data, 'gemini');
	}

	/* ================= HUGGINGFACE ================= */
	private function huggingface($message) {

		$url = 'https://api-inference.huggingface.co/models/' . $this->settings->ai_models;

		return $this->post($url, [
			'Authorization' => 'Bearer ' . $this->settings->huggingface_api_key
		], ['inputs' => $message], 'huggingface');
	}

	/* ================= COHERE ================= */
	private function cohere($message) {

		$url = 'https://api.cohere.ai/v1/chat';

		$data = [
			'model'       => $this->settings->ai_models,
			'message'     => $message,
			'temperature' => (float)$this->settings->temperature,
		];

		return $this->post($url, [
			'Authorization' => 'Bearer ' . $this->settings->cohere_api_key
		], $data, 'cohere');
	}

	/* ================= DEEPSEEK ================= */
	private function deepseek($message) {

		$url = 'https://api.deepseek.com/chat/completions';

		$data = [
			'model'    => $this->settings->ai_models,
			'messages' => [['role' => 'user', 'content' => $message]]
		];

		return $this->post($url, [
			'Authorization' => 'Bearer ' . $this->settings->deepseek_api_key
		], $data, 'deepseek');
	}

	/* ================= COMMON POST ================= */
	private function post($url, $headers, $data, $provider) {

		$args = [
			'headers' => array_merge([
				'Content-Type' => 'application/json'
			], $headers),
			'body'    => wp_json_encode($data),
			'method'  => 'POST',
			'timeout' => 30,
		];

		$response = wp_remote_post($url, $args);

		if (is_wp_error($response)) {
			return $response->get_error_message();
		}

		$body = json_decode(wp_remote_retrieve_body($response), true);

		return $this->extract_reply($body, $provider);
	}

	/* ================= RESPONSE PARSER ================= */
	private function extract_reply($body, $provider) {

		switch ($provider) {

			case 'openai':
			case 'deepseek':
				return isset($body['choices'][0]['message']['content'])
					? $body['choices'][0]['message']['content']
					: 'No response';

			case 'claude':
				return isset($body['content'][0]['text'])
					? $body['content'][0]['text']
					: 'No response';

			case 'gemini':
				return isset($body['candidates'][0]['content']['parts'][0]['text'])
					? $body['candidates'][0]['content']['parts'][0]['text']
					: 'No response';

			case 'huggingface':
				return isset($body[0]['generated_text'])
					? $body[0]['generated_text']
					: 'No response';

			case 'cohere':
				return isset($body['text'])
					? $body['text']
					: 'No response';

			default:
				return 'Invalid provider';
		}
	}

}