<?php

namespace Hostinger\LlmsTxtGenerator;


defined( 'ABSPATH' ) || exit;

class LlmsTxtParser {

    public const DEFAULT_LIMIT               = 100;
    public const HOSTINGER_LLMSTXT_SIGNATURE = '[comment]: # (Generated by Hostinger Tools Plugin)';

    public function get_by_post_type( string $post_type, int $limit = self::DEFAULT_LIMIT, int $offset = 0 ): array {
        $limit = apply_filters( 'hostinger_batch_item_limit', $limit );
        $args  = array(
            'post_type'      => $post_type,
            'post_status'    => 'publish',
            'fields'         => 'ids',
            'posts_per_page' => $limit,
            'offset'         => $offset,
        );

        return get_posts( $args );
    }

    public function get_items( array $items ): string {
        $content = '';
        foreach ( $items as $item ) {
            $post      = get_post( $item );
            $title     = $post->post_title;
            $permalink = get_permalink( $post );
            $excerpt   = $this->prepare_excerpt( $post );

            $content .= "- [$title]($permalink)";
            if ( $excerpt ) {
                $content .= ": $excerpt";
            }

            $content .= "\n";
        }

        return $content;
    }

    public function inject_site_description(): string {
        $description = get_bloginfo( 'description' );

        return $description ? "> $description\n\n" : '';
    }

    public function inject_title(): string {
        $title = get_bloginfo( 'name' ) ? get_bloginfo( 'name' ) : site_url();

        return "# $title\n\n";
    }

    public function inject_signature(): string {
        return "\n\n" . self::HOSTINGER_LLMSTXT_SIGNATURE;
    }

    public function inject_mcp_agent_entry(): string {
        $domain = parse_url( site_url(), PHP_URL_HOST );

        return "- [Agent (MCP protocol)](websites-agents.hostinger.com/$domain/mcp)";
    }

    public function inject_items( array $items, string $title ): string {
        if ( empty( $items ) ) {
            return '';
        }

        $content  = "\n## $title\n\n";
        $content .= $this->get_items( $items );

        return $content;
    }

    public function inject_optional_entries( array $entries ): string {
        $output = '';

        if ( ! empty( $entries ) ) {
            $output  = "\n## Optional\n\n";
            $output .= implode( "\n", $entries );
        }

        return $output;
    }

    public function prepare_excerpt( \WP_Post $item ): string {
        return str_replace( array( "\r", "\n" ), ' ', strip_tags( wp_trim_excerpt( $item->post_excerpt, $item ) ) );
    }
}
