<?php

namespace Hostinger\LlmsTxtGenerator;

use Hostinger\Admin\Jobs\LlmsTxtInjectContentJob;
use Hostinger\Admin\PluginSettings;

defined( 'ABSPATH' ) || exit;

class LlmsTxtGenerator {

    public const HOSTINGER_LLMSTXT_SIGNATURE            = '[comment]: # (Generated by Hostinger Tools Plugin)';
    protected const UTF8_BOM                            = "\xEF\xBB\xBF";
    public const HOSTINGER_LLMSTXT_SUPPORTED_POST_TYPES = array(
        'post'    => 'Posts',
        'page'    => 'Pages',
        'product' => 'Products',
    );

    /**
     * Activation and deactivation hooks appears too early,
     * so the plugin status is not available yet.
     *
     * That's why we use a flag this->woocommerce_status to know the plugin status.
     *
     * @var string|null
     */
    protected ?string $woocommerce_status = null;
    protected PluginSettings $plugin_settings;
    protected LlmsTxtFileHelper $file_helper;
    protected LlmsTxtParser $parser;

    public function __construct( PluginSettings $plugin_settings, LlmsTxtFileHelper $llmstxt_file_helper, LlmsTxtParser $llms_txt_parser ) {
        $this->plugin_settings = $plugin_settings;
        $this->file_helper     = $llmstxt_file_helper;
        $this->parser          = $llms_txt_parser;
        add_action( 'init', array( $this, 'init' ) );
    }

    public function on_woocommerce_activation(): void {
        $this->woocommerce_status = 'active';
        $this->generate();
    }

    public function on_woocommerce_deactivation(): void {
        $this->woocommerce_status = 'inactive';
        $this->generate();
    }

    public function init(): void {
        if ( wp_doing_ajax() || wp_doing_cron() || ! current_user_can( 'manage_options' ) ) {
            return;
        }

        $settings = $this->plugin_settings->get_plugin_settings();

        if ( $settings->get_enable_llms_txt() && ! $this->file_helper->llmstxt_file_exists() ) {
            $this->generate();
        }

        $this->init_hooks();
    }

    public function on_settings_update( bool $is_enabled ): void {
        if ( $is_enabled ) {
            $this->generate();
        } else {
            $this->delete();
        }
    }

    public function on_post_status_change( string $new_status, string $old_status, \WP_Post $post ): void {
        if ( ! $this->is_post_type_supported( $post->post_type ) ) {
            return;
        }

        if ( $new_status === 'publish' || $old_status === 'publish' ) {
            $this->generate();
        }
    }

    public function on_blog_change( mixed $old_value, mixed $new_value ): void {
        if ( $old_value !== $new_value ) {
            $this->generate();
        }
    }

    public function get_content(): string {
        $content  = self::UTF8_BOM;
        $content .= $this->parser->inject_title();
        $content .= $this->parser->inject_site_description();
        $content .= $this->parser->inject_items( $this->parser->get_by_post_type( 'post' ), 'Posts' );
        $content .= $this->parser->inject_items( $this->parser->get_by_post_type( 'page' ), 'Pages' );
        $content .= $this->maybe_inject_woocommerce_products();
        $content .= $this->maybe_inject_optional_entries();
        $content .= $this->parser->inject_signature();

        return $content;
    }

    public function init_hooks(): void {
        add_action( 'transition_post_status', array( $this, 'on_post_status_change' ), 10, 3 );
        add_action( 'hostinger_tools_settings_saved', array( $this, 'on_settings_saved' ) );
        add_action( 'update_option_blogname', array( $this, 'on_blog_change' ), 10, 2 );
        add_action( 'update_option_blogdescription', array( $this, 'on_blog_change' ), 10, 2 );
        add_action( 'activate_woocommerce/woocommerce.php', array( $this, 'on_woocommerce_activation' ) );
        add_action( 'deactivate_woocommerce/woocommerce.php', array( $this, 'on_woocommerce_deactivation' ) );
    }

    public function on_settings_saved( array $settings ): void {
        if ( $settings['enable_llms_txt'] ) {
            $this->generate();
        } else {
            $this->delete();
        }
    }

    public function generate(): void {
        $this->file_helper->create( $this->get_content() );
        do_action( LlmsTxtInjectContentJob::JOB_NAME, array( 'post_type' => 'post' ) );
        do_action( LlmsTxtInjectContentJob::JOB_NAME, array( 'post_type' => 'page' ) );

        if ( $this->is_woocommerce_active() ) {
            do_action( LlmsTxtInjectContentJob::JOB_NAME, array( 'post_type' => 'product' ) );
        }
    }

    protected function delete(): void {
        $this->file_helper->delete();
    }

    protected function is_post_type_supported( string $post_type ): bool {
        return array_key_exists( $post_type, self::HOSTINGER_LLMSTXT_SUPPORTED_POST_TYPES );
    }

    protected function is_woocommerce_active(): bool {
        return ( is_null( $this->woocommerce_status ) && is_plugin_active( 'woocommerce/woocommerce.php' ) ) || $this->woocommerce_status === 'active';
    }

    protected function maybe_inject_woocommerce_products(): string {
        if ( ! $this->is_woocommerce_active() ) {
            return '';
        }

        return $this->parser->inject_items( $this->parser->get_by_post_type( 'product' ), 'Products' );
    }

    protected function maybe_inject_optional_entries(): string {
        $entries   = array();
        $mcp_entry = $this->maybe_inject_mcp_agent_entry();

        if ( $mcp_entry ) {
            $entries[] = $mcp_entry;
        }

        return $this->parser->inject_optional_entries( $entries );
    }

    protected function maybe_inject_mcp_agent_entry(): string {
        $settings = $this->plugin_settings->get_plugin_settings();
        if ( ! $settings->get_optin_mcp() ) {
            return '';
        }

        return $this->parser->inject_mcp_agent_entry();
    }
}
