<?php
if (!defined('ABSPATH')) exit;

class SS_LLMS {

    public static function init() {
        add_action('template_redirect', [__CLASS__, 'maybe_serve']);
    }

    public static function maybe_serve() {
        $request_uri = isset($_SERVER['REQUEST_URI'])
            ? sanitize_text_field(wp_unslash($_SERVER['REQUEST_URI']))
            : '';

        if (trim($request_uri, '/') !== 'llms.txt') {
            return;
        }

        // If a real file exists at docroot, let WP serve it normally
        if (file_exists(ABSPATH . 'llms.txt')) {
            return;
        }

        if (class_exists('SS_AI_Protocol')) {
            $payload = SS_AI_Protocol::preview_llms() . "\n";

            header('Content-Type: text/plain; charset=utf-8');
            header('X-Robots-Tag: all');

            echo esc_textarea($payload);
            exit;
        }
    }
}
