<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}
class SS_LLMS {

    public static function init(){
        // Register query var/tag on every load so get_query_var('ss_llms') is recognized
        add_filter('query_vars', [__CLASS__, 'register_query_var']);
        add_action('init',       [__CLASS__, 'register_rewrite']);
        add_action('template_redirect', [__CLASS__, 'serve']);

        // Fallback: if rewrites aren’t flushed yet, short-circuit 404 to serve llms.txt
        add_filter('pre_handle_404', [__CLASS__, 'fallback_serve_on_404'], 10, 2);
    }

    /** Feature flag check */
    private static function llms_enabled(): bool {
        $flags = (array) get_option(SS_Settings::OPT_FEATURE_FLAGS, []);
        return in_array('llms', $flags, true);
    }

    /** Ensure WP will accept ss_llms as a public query var */
    public static function register_query_var($vars){
        $vars[] = 'ss_llms';
        return $vars;
    }

    /** Add rewrite rule/tag (only when enabled) */
    public static function register_rewrite(){
        if (!self::llms_enabled()) return;

        // Map /llms.txt -> index.php?ss_llms=1
        add_rewrite_tag('%ss_llms%', '(1)');
        add_rewrite_rule('^llms\.txt$', 'index.php?ss_llms=1', 'top');
        // Note: flushing is handled when the feature flag changes (SS_Settings::on_flags_updated)
    }

    /** Normal serving path when rewrite works */
    public static function serve(){
        if (!self::llms_enabled()) return;

        if (get_query_var('ss_llms')) {
            self::output_llms();
            exit; // <— ensure theme does not render
        }
    }

    /**
     * Fallback: if WP is about to send a 404 but the request path ends with /llms.txt,
     * serve our content anyway and stop execution.
     */
    public static function fallback_serve_on_404( $preempt, $wp_query ) {

        if ( ! self::llms_enabled() ) {
            return $preempt;
        }

        // Safely read and sanitize REQUEST_URI
        $req_uri = '';
        if ( isset( $_SERVER['REQUEST_URI'] ) ) {
            $req_uri = sanitize_text_field(
                wp_unslash( $_SERVER['REQUEST_URI'] )
            );
        }

        if ( empty( $req_uri ) ) {
            return $preempt;
        }

        // Use wp_parse_url instead of parse_url
        $parsed = wp_parse_url( $req_uri );
        $path   = isset( $parsed['path'] ) ? $parsed['path'] : '';

        if ( strtolower( basename( $path ) ) === 'llms.txt' ) {
            self::output_llms();
            exit; // IMPORTANT: stop WP/theme execution
        }

        return $preempt;
    }


    /** Output the plain text body */
    private static function output_llms(){
        // Avoid caching plugins buffering as HTML
        if (!headers_sent()){
            header('Content-Type: text/plain; charset=utf-8');
            header('Cache-Control: no-cache, must-revalidate');
        }
        echo esc_html(
            '# llms.txt generated by SearchShifter v' . SEARCHSHIFTER_VERSION . "\n"
        );
        echo "# List approved content for AI training here.\n";
        // In M3 you can append allowlisted URLs/content from options.
    }
}
