<?php
/**
 * AI-readable text endpoints.
 *
 * @package MicropediaAISearchOptimizer
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/** LLMS endpoints. */
class Micropedia_AI_Llms {
	/** Init hooks. */
	public static function init() {
		add_action( 'template_redirect', array( __CLASS__, 'maybe_render_endpoint' ) );
		add_action( 'save_post', array( __CLASS__, 'clear_cache' ) );
	}

	/** Render endpoint when URL matches. */
	public static function maybe_render_endpoint() {
		$path = isset( $_SERVER['REQUEST_URI'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '';
		$path = (string) wp_parse_url( $path, PHP_URL_PATH );

		if ( '/llms.txt' === $path && micropedia_ai_get_option( 'enable_llms', 1 ) ) {
			self::output_text( self::get_llms() );
		}

		if ( '/llms-full.txt' === $path && micropedia_ai_get_option( 'enable_llms_full', 0 ) ) {
			self::output_text( self::get_llms_full() );
		}
	}

	/** Clear cached AI text endpoints when content changes. */
	public static function clear_cache() {
		delete_transient( 'micropedia_ai_llms_txt' );
		delete_transient( 'micropedia_ai_llms_full_txt' );
	}

	/**
	 * Output text/plain safely.
	 *
	 * @param string $body Body.
	 */
	private static function output_text( $body ) {
		status_header( 200 );
		nocache_headers();
		header( 'Content-Type: text/plain; charset=utf-8' );
		echo esc_html( $body );
		exit;
	}

	/**
	 * Get cached llms.txt body.
	 *
	 * @return string
	 */
	public static function get_llms() {
		$cache_key = 'micropedia_ai_llms_txt';
		$cached    = get_transient( $cache_key );
		if ( is_string( $cached ) ) {
			return $cached;
		}

		$limit = absint( micropedia_ai_get_option( 'posts_limit', 20 ) );
		$limit = min( max( $limit, 1 ), 100 );
		$body  = '# ' . wp_strip_all_tags( get_bloginfo( 'name' ) ) . "\n\n";
		$body .= wp_strip_all_tags( get_bloginfo( 'description' ) ) . "\n\n";
		$body .= "Disclaimer: This file improves readability for AI systems but does not guarantee inclusion, ranking, indexing, traffic, visibility, or citation.\n\n";

		$pages = get_pages( array( 'sort_column' => 'menu_order,post_title', 'number' => 20 ) );
		if ( ! empty( $pages ) ) {
			$body .= "## Main Pages\n";
			foreach ( $pages as $page ) {
				$body .= '- ' . wp_strip_all_tags( get_the_title( $page ) ) . ': ' . esc_url_raw( get_permalink( $page ) ) . "\n";
			}
			$body .= "\n";
		}

		$posts = get_posts( array( 'numberposts' => $limit, 'post_status' => 'publish' ) );
		if ( ! empty( $posts ) ) {
			$body .= "## Recent Posts\n";
			foreach ( $posts as $post ) {
				$body .= '- ' . wp_strip_all_tags( get_the_title( $post ) ) . ': ' . esc_url_raw( get_permalink( $post ) ) . "\n";
			}
			$body .= "\n";
		}

		$categories = get_categories( array( 'hide_empty' => true, 'number' => 50 ) );
		if ( ! empty( $categories ) ) {
			$body .= "## Categories\n";
			foreach ( $categories as $category ) {
				$body .= '- ' . wp_strip_all_tags( $category->name ) . ': ' . esc_url_raw( get_category_link( $category ) ) . "\n";
			}
		}

		set_transient( $cache_key, $body, absint( micropedia_ai_get_option( 'cache_ttl', HOUR_IN_SECONDS ) ) );
		return $body;
	}

	/**
	 * Get cached llms-full.txt body.
	 *
	 * @return string
	 */
	public static function get_llms_full() {
		$cache_key = 'micropedia_ai_llms_full_txt';
		$cached    = get_transient( $cache_key );
		if ( is_string( $cached ) ) {
			return $cached;
		}

		$limit = absint( micropedia_ai_get_option( 'posts_limit', 20 ) );
		$limit = min( max( $limit, 1 ), 100 );
		$posts = get_posts( array( 'numberposts' => $limit, 'post_status' => 'publish', 'post_type' => array( 'post', 'page' ) ) );
		$body  = '# ' . wp_strip_all_tags( get_bloginfo( 'name' ) ) . " - Full AI-readable content\n\n";
		$body .= "Disclaimer: This file improves readability for AI systems but does not guarantee inclusion, ranking, indexing, traffic, visibility, or citation.\n\n";

		foreach ( $posts as $post ) {
			$content = get_post_field( 'post_content', $post );
			$content = strip_shortcodes( $content );
			$content = wp_strip_all_tags( apply_filters( 'the_content', $content ) );
			$body   .= "## " . wp_strip_all_tags( get_the_title( $post ) ) . "\n";
			$body   .= 'URL: ' . esc_url_raw( get_permalink( $post ) ) . "\n";
			$body   .= 'Author: ' . wp_strip_all_tags( get_the_author_meta( 'display_name', (int) $post->post_author ) ) . "\n";
			$body   .= 'Date: ' . wp_strip_all_tags( get_the_date( 'c', $post ) ) . "\n\n";
			$body   .= trim( $content ) . "\n\n---\n\n";
		}

		set_transient( $cache_key, $body, absint( micropedia_ai_get_option( 'cache_ttl', HOUR_IN_SECONDS ) ) );
		return $body;
	}
}
