<?php

namespace RistrettoApps\Spawnster\Services;

/**
 * Provides content research and summarization functionality.
 *
 * @package    Spawnster
 * @subpackage Spawnster/Services
 * @author     Ristretto Apps
 */
class ContentResearchService {

	/**
	 * The Google Search Service instance.
	 *
	 * @var GoogleSearchService
	 */
	private $google_search_service;

	/**
	 * The OpenAI Service instance.
	 *
	 * @var OpenAiService
	 */
	private $openai_service;

	/**
	 * Constructor for the ContentResearchService class.
	 *
	 * @param GoogleSearchService $google_search_service The Google Search Service instance.
	 * @param OpenAiService       $openai_service       The OpenAI Service instance.
	 */
	public function __construct( GoogleSearchService $google_search_service, OpenAiService $openai_service ) {
		$this->google_search_service = $google_search_service;
		$this->openai_service = $openai_service;
	}

	/**
	 * Fetch and summarize content related to a topic.
	 *
	 * @param string $topic                    The topic to research.
	 * @param int    $category_id              The category ID.
	 * @param int    $number_of_past_articles  The number of articles to fetch.
	 * @return array                           The summarized content.
	 */
	public function fetch_and_summarize_content( string $topic, int $category_id, int $number_of_past_articles ): array {
		// Fetch content from Google Search
		$search_results = $this->google_search_service->search( $topic, $number_of_past_articles );
		
		if ( is_wp_error( $search_results ) ) {
			return array();
		}

		// Extract content from search results
		$contents = $this->google_search_service->extract_content_from_results( $search_results );

		// Summarize the contents
		return $this->summarize_contents( $contents );
	}

	/**
	 * Summarize a list of contents.
	 *
	 * @param array $contents The contents to summarize.
	 * @return array The summarized contents.
	 */
	public function summarize_contents( array $contents ): array {
		$summarized_contents = array();

		foreach ( $contents as $content ) {
			$summary = $this->summarize_single_content( $content );
			if ( $summary ) {
				$summarized_contents[] = array(
					'title'   => $content['title'] ?? '',
					'summary' => $summary,
					'link'    => $content['link'] ?? '',
				);
			}
		}

		return $summarized_contents;
	}

	/**
	 * Summarize a single content piece.
	 *
	 * @param array $content The content to summarize.
	 * @return string|false The summary or false on failure.
	 */
	private function summarize_single_content( array $content ): string|false {
		$text_to_summarize = '';

		// Use full content if available, otherwise use snippet
		if ( ! empty( $content['full_content'] ) ) {
			$text_to_summarize = $content['full_content'];
		} elseif ( ! empty( $content['snippet'] ) ) {
			$text_to_summarize = $content['snippet'];
		} else {
			return false;
		}

		// Limit text length to avoid token limits
		$text_to_summarize = substr( $text_to_summarize, 0, 4000 );

		$language_instruction = $this->openai_service->get_language_instruction();
		$prompt = sprintf(
			'Please provide a concise summary of the following content in 2-3 sentences. Focus on the key points and main ideas:\n\n%s%s',
			$text_to_summarize,
			$language_instruction
		);

		$result = $this->openai_service->generate_response_with_options( $prompt, array(
			'max_tokens' => 200,
			'temperature' => 0.3,
		) );

		if ( is_wp_error( $result ) ) {
			return false;
		}

		return $result['choices'][0]['message']['content'] ?? false;
	}

	/**
	 * Generate a new topic based on existing content and category.
	 *
	 * @param string $job_id                The job ID.
	 * @param string $specific_topic        The specific topic.
	 * @param int    $category              The category ID.
	 * @param array  $summarized_contents   The summarized contents.
	 * @return string                       The generated topic.
	 */
	public function generate_new_topic( string $job_id, string $specific_topic, int $category, array $summarized_contents ): string {
		$category_name = get_cat_name( $category );
		
		// Create context from summarized contents
		$context = '';
		foreach ( $summarized_contents as $content ) {
			$context .= "- " . $content['summary'] . "\n";
		}

		$language_instruction = $this->openai_service->get_language_instruction();
		$prompt = sprintf(
			'Based on the following research context about "%s" in the category "%s", generate a new, engaging blog post topic that is relevant and timely. The topic should be specific, interesting, and provide value to readers.\n\nResearch Context:\n%s\n\nGenerate a single, compelling topic title:%s',
			$specific_topic,
			$category_name,
			$context,
			$language_instruction
		);

		$result = $this->openai_service->generate_response_with_options( $prompt, array(
			'max_tokens' => 100,
			'temperature' => 0.7,
		) );

		if ( is_wp_error( $result ) ) {
			return $specific_topic; // Fallback to original topic
		}

		return trim( $result['choices'][0]['message']['content'] ?? $specific_topic );
	}
} 