<?php
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;

        // REQUEST_URI may include subdirectory (e.g. /wordpress/llms.txt); check basename.
        $req_uri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';
        if ($req_uri && strtolower(basename(parse_url($req_uri, PHP_URL_PATH))) === 'llms.txt') {
            self::output_llms();
            exit;        // <— IMPORTANT: terminate so WP/theme cannot add HTML/admin-bar
        }
        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 "# 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.
    }
}
