<?php
/**
 * REST API Functionality
 *
 * @package HDSofT\AISummary
 */

namespace HDSofT\AISummary;

// Prevent direct access
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * REST API Class
 */
class RestAPI {

    /**
     * API namespace
     */
    const NAMESPACE = 'hdsoft-ai-summary/v1';

    /**
     * Constructor
     */
    public function __construct() {
        add_action( 'rest_api_init', array( $this, 'register_routes' ) );
    }

    /**
     * Register REST API routes
     */
    public function register_routes() {
        // Generate summary endpoint
        register_rest_route(
            self::NAMESPACE,
            '/generate',
            array(
                'methods'             => 'POST',
                'callback'            => array( $this, 'generate_summary' ),
                'permission_callback' => array( $this, 'check_generate_permissions' ),
                'args'                => array(
                    'post_id' => array(
                        'required'          => true,
                        'type'              => 'integer',
                        'minimum'           => 1,
                        'sanitize_callback' => 'absint',
                        'validate_callback' => array( $this, 'validate_post_id' ),
                    ),
                    'force_regenerate' => array(
                        'required'          => false,
                        'type'              => 'boolean',
                        'default'           => false,
                        'sanitize_callback' => 'rest_sanitize_boolean',
                    ),
                ),
            )
        );

        // Test connection endpoint
        register_rest_route(
            self::NAMESPACE,
            '/test-connection',
            array(
                'methods'             => 'POST',
                'callback'            => array( $this, 'test_connection' ),
                'permission_callback' => array( $this, 'check_admin_permissions' ),
            )
        );

        // Get summary endpoint
        register_rest_route(
            self::NAMESPACE,
            '/summary/(?P<post_id>\d+)',
            array(
                'methods'             => 'GET',
                'callback'            => array( $this, 'get_summary' ),
                'permission_callback' => array( $this, 'check_read_permissions' ),
                'args'                => array(
                    'post_id' => array(
                        'required'          => true,
                        'type'              => 'integer',
                        'minimum'           => 1,
                        'sanitize_callback' => 'absint',
                        'validate_callback' => array( $this, 'validate_post_id' ),
                    ),
                ),
            )
        );

        // Delete summary endpoint
        register_rest_route(
            self::NAMESPACE,
            '/summary/(?P<post_id>\d+)',
            array(
                'methods'             => 'DELETE',
                'callback'            => array( $this, 'delete_summary' ),
                'permission_callback' => array( $this, 'check_edit_permissions' ),
                'args'                => array(
                    'post_id' => array(
                        'required'          => true,
                        'type'              => 'integer',
                        'minimum'           => 1,
                        'sanitize_callback' => 'absint',
                        'validate_callback' => array( $this, 'validate_post_id' ),
                    ),
                ),
            )
        );
    }

    /**
     * Generate summary endpoint callback
     *
     * @param WP_REST_Request $request Request object.
     * @return WP_REST_Response|WP_Error
     */
    public function generate_summary( $request ) {
        $post_id = $request->get_param( 'post_id' );
        $force_regenerate = $request->get_param( 'force_regenerate' );

        $post = get_post( $post_id );
        if ( ! $post ) {
            return new \WP_Error(
                'post_not_found',
                __( 'Post not found.', 'hd-soft-ai-summary' ),
                array( 'status' => 404 )
            );
        }

        // Check if post is published
        if ( 'publish' !== $post->post_status ) {
            return new \WP_Error(
                'post_not_published',
                __( 'Post must be published to generate summary.', 'hd-soft-ai-summary' ),
                array( 'status' => 400 )
            );
        }

        $plugin = Plugin::get_instance();

        // Check if summary already exists and force_regenerate is false
        if ( ! $force_regenerate && $plugin->has_summary( $post_id ) ) {
            $existing_summary = $plugin->get_summary( $post_id );
            return rest_ensure_response(
                array(
                    'success' => true,
                    'summary' => $existing_summary,
                    'hash'    => get_post_meta( $post_id, '_hdsoft_ai_summary_hash', true ),
                    'message' => __( 'Existing summary returned. Use force_regenerate=true to create a new one.', 'hd-soft-ai-summary' ),
                )
            );
        }

        // Generate new summary
        $summary = $plugin->generate_summary( $post_id, $post );

        if ( is_wp_error( $summary ) ) {
            return new \WP_Error(
                'generation_failed',
                $summary->get_error_message(),
                array( 'status' => 500 )
            );
        }

        if ( false === $summary ) {
            return new \WP_Error(
                'generation_failed',
                __( 'Failed to generate summary.', 'hd-soft-ai-summary' ),
                array( 'status' => 500 )
            );
        }

        return rest_ensure_response(
            array(
                'success' => true,
                'summary' => $summary,
                'hash'    => $plugin->generate_content_hash( $post ),
                'message' => __( 'Summary generated successfully.', 'hd-soft-ai-summary' ),
            )
        );
    }

    /**
     * Test connection endpoint callback
     *
     * @param WP_REST_Request $request Request object.
     * @return WP_REST_Response|WP_Error
     */
    public function test_connection( $request ) {
        $plugin = Plugin::get_instance();
        $result = $plugin->openrouter->test_connection();

        if ( is_wp_error( $result ) ) {
            return new \WP_Error(
                'connection_failed',
                $result->get_error_message(),
                array( 'status' => 400 )
            );
        }

        return rest_ensure_response( $result );
    }

    /**
     * Get summary endpoint callback
     *
     * @param WP_REST_Request $request Request object.
     * @return WP_REST_Response|WP_Error
     */
    public function get_summary( $request ) {
        $post_id = $request->get_param( 'post_id' );

        $post = get_post( $post_id );
        if ( ! $post ) {
            return new \WP_Error(
                'post_not_found',
                __( 'Post not found.', 'hd-soft-ai-summary' ),
                array( 'status' => 404 )
            );
        }

        $plugin = Plugin::get_instance();
        $summary = $plugin->get_summary( $post_id );

        if ( ! $summary ) {
            return new \WP_Error(
                'summary_not_found',
                __( 'No summary found for this post.', 'hd-soft-ai-summary' ),
                array( 'status' => 404 )
            );
        }

        $hash = get_post_meta( $post_id, '_hdsoft_ai_summary_hash', true );
        $is_manual = get_post_meta( $post_id, '_hdsoft_ai_summary_manual', true );
        $current_hash = $plugin->generate_content_hash( $post );

        return rest_ensure_response(
            array(
                'success'         => true,
                'summary'         => $summary,
                'hash'            => $hash,
                'current_hash'    => $current_hash,
                'is_manual'       => (bool) $is_manual,
                'content_changed' => $hash !== $current_hash,
            )
        );
    }

    /**
     * Delete summary endpoint callback
     *
     * @param WP_REST_Request $request Request object.
     * @return WP_REST_Response|WP_Error
     */
    public function delete_summary( $request ) {
        $post_id = $request->get_param( 'post_id' );

        $post = get_post( $post_id );
        if ( ! $post ) {
            return new \WP_Error(
                'post_not_found',
                __( 'Post not found.', 'hd-soft-ai-summary' ),
                array( 'status' => 404 )
            );
        }

        $plugin = Plugin::get_instance();
        
        if ( ! $plugin->has_summary( $post_id ) ) {
            return new \WP_Error(
                'summary_not_found',
                __( 'No summary found for this post.', 'hd-soft-ai-summary' ),
                array( 'status' => 404 )
            );
        }

        $plugin->delete_summary( $post_id );

        return rest_ensure_response(
            array(
                'success' => true,
                'message' => __( 'Summary deleted successfully.', 'hd-soft-ai-summary' ),
            )
        );
    }

    /**
     * Check permissions for generating summaries
     *
     * @param WP_REST_Request $request Request object.
     * @return bool|WP_Error
     */
    public function check_generate_permissions( $request ) {
        $post_id = $request->get_param( 'post_id' );

        if ( ! current_user_can( 'edit_posts' ) ) {
            return new \WP_Error(
                'rest_forbidden',
                __( 'You do not have permission to generate summaries.', 'hd-soft-ai-summary' ),
                array( 'status' => 403 )
            );
        }

        if ( $post_id && ! current_user_can( 'edit_post', $post_id ) ) {
            return new \WP_Error(
                'rest_forbidden',
                __( 'You do not have permission to edit this post.', 'hd-soft-ai-summary' ),
                array( 'status' => 403 )
            );
        }

        return true;
    }

    /**
     * Check permissions for editing summaries
     *
     * @param WP_REST_Request $request Request object.
     * @return bool|WP_Error
     */
    public function check_edit_permissions( $request ) {
        return $this->check_generate_permissions( $request );
    }

    /**
     * Check permissions for reading summaries
     *
     * @param WP_REST_Request $request Request object.
     * @return bool|WP_Error
     */
    public function check_read_permissions( $request ) {
        $post_id = $request->get_param( 'post_id' );

        if ( $post_id ) {
            $post = get_post( $post_id );
            if ( ! $post ) {
                return new \WP_Error(
                    'post_not_found',
                    __( 'Post not found.', 'hd-soft-ai-summary' ),
                    array( 'status' => 404 )
                );
            }

            // Check if post is publicly readable or user has edit permissions
            if ( 'publish' !== $post->post_status && ! current_user_can( 'edit_post', $post_id ) ) {
                return new \WP_Error(
                    'rest_forbidden',
                    __( 'You do not have permission to read this post summary.', 'hd-soft-ai-summary' ),
                    array( 'status' => 403 )
                );
            }
        }

        return true;
    }

    /**
     * Check admin permissions
     *
     * @param WP_REST_Request $request Request object.
     * @return bool|WP_Error
     */
    public function check_admin_permissions( $request ) {
        if ( ! current_user_can( 'manage_options' ) ) {
            return new \WP_Error(
                'rest_forbidden',
                __( 'You do not have permission to access this endpoint.', 'hd-soft-ai-summary' ),
                array( 'status' => 403 )
            );
        }

        return true;
    }

    /**
     * Validate post ID
     *
     * @param int             $value   Post ID.
     * @param WP_REST_Request $request Request object.
     * @param string          $param   Parameter name.
     * @return bool|WP_Error
     */
    public function validate_post_id( $value, $request, $param ) {
        if ( ! is_numeric( $value ) || $value <= 0 ) {
            return new \WP_Error(
                'invalid_post_id',
                __( 'Post ID must be a positive integer.', 'hd-soft-ai-summary' ),
                array( 'status' => 400 )
            );
        }

        $post = get_post( $value );
        if ( ! $post ) {
            return new \WP_Error(
                'post_not_found',
                __( 'Post not found.', 'hd-soft-ai-summary' ),
                array( 'status' => 404 )
            );
        }

        // Check if post type is supported
        $supported_post_types = apply_filters( 'hdsoft_ai_summary_supported_post_types', array( 'post' ) );
        if ( ! in_array( $post->post_type, $supported_post_types, true ) ) {
            return new \WP_Error(
                'unsupported_post_type',
                __( 'This post type is not supported for AI summaries.', 'hd-soft-ai-summary' ),
                array( 'status' => 400 )
            );
        }

        return true;
    }

    /**
     * Get API schema for generate endpoint
     *
     * @return array
     */
    public function get_generate_schema() {
        return array(
            '$schema'    => 'http://json-schema.org/draft-04/schema#',
            'title'      => 'Generate Summary',
            'type'       => 'object',
            'properties' => array(
                'post_id' => array(
                    'description' => __( 'The post ID to generate summary for.', 'hd-soft-ai-summary' ),
                    'type'        => 'integer',
                    'minimum'     => 1,
                ),
                'force_regenerate' => array(
                    'description' => __( 'Whether to force regeneration of existing summary.', 'hd-soft-ai-summary' ),
                    'type'        => 'boolean',
                    'default'     => false,
                ),
            ),
            'required'   => array( 'post_id' ),
        );
    }

    /**
     * Get API schema for summary endpoint
     *
     * @return array
     */
    public function get_summary_schema() {
        return array(
            '$schema'    => 'http://json-schema.org/draft-04/schema#',
            'title'      => 'Post Summary',
            'type'       => 'object',
            'properties' => array(
                'success' => array(
                    'description' => __( 'Whether the request was successful.', 'hd-soft-ai-summary' ),
                    'type'        => 'boolean',
                ),
                'summary' => array(
                    'description' => __( 'The generated summary text.', 'hd-soft-ai-summary' ),
                    'type'        => 'string',
                ),
                'hash' => array(
                    'description' => __( 'Content hash when summary was generated.', 'hd-soft-ai-summary' ),
                    'type'        => 'string',
                ),
                'current_hash' => array(
                    'description' => __( 'Current content hash.', 'hd-soft-ai-summary' ),
                    'type'        => 'string',
                ),
                'is_manual' => array(
                    'description' => __( 'Whether the summary was manually edited.', 'hd-soft-ai-summary' ),
                    'type'        => 'boolean',
                ),
                'content_changed' => array(
                    'description' => __( 'Whether content has changed since summary generation.', 'hd-soft-ai-summary' ),
                    'type'        => 'boolean',
                ),
            ),
        );
    }
}
