<?php
/**
 * Robots.txt integration class
 *
 * Injects llms.txt reference into robots.txt via WordPress filter
 * or physical file write.
 *
 * @package LLMagnet_AI_SEO_Optimizer
 */

namespace LLMagnet_AI_SEO_Optimizer;

class Robots_Txt {

    /**
     * Initialize hooks
     *
     * @return void
     */
    public function init(): void {
        if ( get_option( 'llmagnet_robots_txt_inject', true ) ) {
            add_filter( 'robots_txt', [ $this, 'inject_via_filter' ], 10, 2 );
        }

        add_action( 'rest_api_init', [ $this, 'register_rest_routes' ] );
    }

    /**
     * Register REST API routes
     *
     * @return void
     */
    public function register_rest_routes(): void {
        register_rest_route( 'llm-analytics/v1', '/robots-status', [
            'methods'             => 'GET',
            'callback'            => [ $this, 'rest_get_status' ],
            'permission_callback' => function () {
                return current_user_can( 'manage_options' );
            },
        ] );

        register_rest_route( 'llm-analytics/v1', '/robots-inject', [
            'methods'             => 'POST',
            'callback'            => [ $this, 'rest_inject' ],
            'permission_callback' => function () {
                return current_user_can( 'manage_options' );
            },
        ] );
    }

    /**
     * REST callback: get robots.txt status
     *
     * @return \WP_REST_Response
     */
    public function rest_get_status(): \WP_REST_Response {
        return new \WP_REST_Response( $this->get_status(), 200 );
    }

    /**
     * REST callback: inject llms.txt reference into physical robots.txt
     *
     * @return \WP_REST_Response
     */
    public function rest_inject(): \WP_REST_Response {
        $status = $this->get_status();
        
        // If already has reference (via filter or file), mark as success
        if ( $status['has_llms_reference'] ) {
            return new \WP_REST_Response( [
                'success' => true,
                'method'  => $status['injection_method'],
                'message' => 'llms.txt reference is already present in robots.txt',
                'status'  => $status,
            ], 200 );
        }
        
        // Try to inject into physical file
        $result = $this->inject_into_physical();

        if ( $result ) {
            return new \WP_REST_Response( [
                'success' => true,
                'method'  => 'file',
                'status'  => $this->get_status(),
            ], 200 );
        }

        // If physical write failed, check if filter method is enabled
        if ( get_option( 'llmagnet_robots_txt_inject', true ) ) {
            return new \WP_REST_Response( [
                'success' => true,
                'method'  => 'filter',
                'message' => 'Using WordPress filter method (no physical file write needed)',
                'status'  => $this->get_status(),
            ], 200 );
        }

        return new \WP_REST_Response( [
            'success' => false,
            'message' => 'Could not write to robots.txt. File may not exist or is not writable.',
        ], 400 );
    }

    /**
     * WordPress filter callback — append llms-txt directive to virtual robots.txt
     *
     * @param string $output Current robots.txt content
     * @param bool   $public Whether the site is public
     * @return string
     */
    public function inject_via_filter( string $output, bool $public ): string {
        if ( ! $public ) {
            return $output;
        }

        $llms_url = home_url( '/llms.txt' );

        if ( strpos( $output, 'llms.txt' ) === false ) {
            $output .= "\n# LLMagnet AI Visibility\nllms-txt: " . esc_url( $llms_url ) . "\n";
        }

        return $output;
    }

    /**
     * Append llms-txt directive to a physical robots.txt file
     *
     * Only called on explicit user action (REST endpoint).
     *
     * @return bool
     */
    public function inject_into_physical(): bool {
        $path = ABSPATH . 'robots.txt';

        if ( ! file_exists( $path ) || ! is_writable( $path ) ) {
            return false;
        }

        $content = Filesystem_Helper::get_contents( $path );
        if ( $content === false ) {
            return false;
        }

        if ( strpos( $content, 'llms.txt' ) !== false ) {
            return true;
        }

        $addition = "\n# LLMagnet AI Visibility\nllms-txt: " . home_url( '/llms.txt' ) . "\n";

        return Filesystem_Helper::put_contents( $path, $content . $addition );
    }

    /**
     * Get current robots.txt status
     *
     * @return array{has_physical_file: bool, has_llms_reference: bool, injection_method: string, robots_txt_url: string}
     */
    public function get_status(): array {
        $physical_path = ABSPATH . 'robots.txt';
        $has_physical  = file_exists( $physical_path );
        $has_reference = false;

        if ( $has_physical ) {
            $content = file_get_contents( $physical_path );
            if ( $content !== false ) {
                $has_reference = strpos( $content, 'llms.txt' ) !== false;
            }
        } else {
            $virtual       = apply_filters( 'robots_txt', '', (bool) get_option( 'blog_public' ) );
            $has_reference = strpos( $virtual, 'llms.txt' ) !== false;
        }

        $inject_enabled = get_option( 'llmagnet_robots_txt_inject', true );

        return [
            'has_physical_file'  => $has_physical,
            'has_llms_reference' => $has_reference,
            'injection_method'   => $inject_enabled ? ( $has_physical ? 'file' : 'filter' ) : 'none',
            'robots_txt_url'     => home_url( '/robots.txt' ),
        ];
    }
}
