<?php

namespace Antimanual\Api;

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use Antimanual\AIProvider;
use Antimanual\AIResponseCleaner;
use Antimanual\PostGenerator;

/**
 * Content rewrite API endpoints.
 */
class ContentController {

    /**
     * Register REST routes for content rewriting.
     *
     * @param string $namespace REST namespace.
     */
    public function register_routes( string $namespace ) {
        register_rest_route( $namespace, '/rewrite-content', [
            'methods'             => 'POST',
            'callback'            => [ $this, 'rewrite_content' ],
            'permission_callback' => fn() => current_user_can( 'manage_options' ),
            'timeout'             => 120,
        ] );

        register_rest_route( $namespace, '/generate-featured-image', [
            'methods'             => 'POST',
            'callback'            => [ $this, 'generate_featured_image' ],
            'permission_callback' => fn() => current_user_can( 'manage_options' ),
            'timeout'             => 120,
        ] );
    }

    /**
     * Rewrite content.
     *
     * @param \WP_REST_Request $request The REST request.
     * @return \WP_REST_Response|\WP_Error The REST response.
     */
    public function rewrite_content( $request ) {
        if ( atml_is_bulk_rewrite_limit_exceeded() ) {
            return new \WP_Error(
                'monthly_limit_exceeded',
                __( 'You have reached your monthly limit of 100 bulk rewrite actions. Upgrade to Pro for unlimited actions.', 'antimanual' )
            );
        }

        $payload = json_decode( $request->get_body(), true );
        $payload = is_array( $payload ) ? $payload : [];

        $post_id = intval( $payload['postId'] ?? 0 );
        $prompt  = trim( strval( $payload['prompt'] ?? '' ) );

        if ( ! $post_id || empty( $prompt ) ) {
            return rest_ensure_response([
                'success' => false,
                'message' => __( 'Post ID and prompt are required.', 'antimanual' ),
            ]);
        }

        $post = get_post( $post_id );

        if ( ! $post ) {
            return rest_ensure_response([
                'success' => false,
                'message' => __( 'Post not found.', 'antimanual' ),
            ]);
        }

        if ( ! current_user_can( 'edit_post', $post_id ) ) {
            return rest_ensure_response([
                'success' => false,
                'message' => __( 'Unauthorized', 'antimanual' ),
            ]);
        }

        $content = $post->post_content;

        $instructions = "You are an expert WordPress content editor and AI writing assistant.\n"
            . "Your task is to rewrite or edit a given WordPress post's content according to the user's prompt.\n\n"
            . "Follow these rules carefully:\n"
            . "1. Keep all valid WordPress block syntax intact (e.g., <!-- wp:paragraph --> ... <!-- /wp:paragraph -->, shortcodes, embeds, HTML tags).\n"
            . "2. Apply the user's instructions exactly — rewrite, enhance, shorten, expand, or change the tone as requested.\n"
            . "3. Do not remove, reorder, or merge block structures unless the user explicitly says so.\n"
            . "4. Preserve factual meaning unless the user asks for creative rewriting.\n"
            . "5. Maintain a natural, human writing style that is clear, engaging, and grammatically correct.\n"
            . "6. Do not include explanations, comments, or any extra text — return only the rewritten WordPress post content.\n"
            . "7. The output must be valid WordPress post content that can be saved directly.\n\n"
            . "Input: USER PROMPT + ORIGINAL POST CONTENT\n"
            . "Output: REWRITTEN POST CONTENT";

        $user_msg = "USER PROMPT:\n"
            . "```md\n"
            . $prompt
            . "\n```\n\n"
            . "ORIGINAL POST CONTENT:\n"
            . "```html\n"
            . $content
            . "\n```";

        $messages = [
            [
                'role'    => 'system',
                'content' => $instructions,
            ],
            [
                'role'    => 'user',
                'content' => $user_msg,
            ],
        ];

        $reply = AIProvider::get_reply( $messages );

        if ( ! is_string( $reply ) ) {
            return rest_ensure_response([
                'success' => false,
                'message' => $reply['error'] ?? __( 'Failed to rewrite content.', 'antimanual' ),
            ]);
        }

        $reply = AIResponseCleaner::clean_gutenberg_content( $reply );

        wp_update_post([
            'ID'           => $post_id,
            'post_content' => $reply,
        ]);

        // Record one usage row per rewrite (for every tier). Free-tier limits
        // are COUNT-based and unaffected; Pro rows feed the Usage & Cost report.
        \Antimanual\UsageTracker::record( 'bulk_rewrite', $user_msg, $reply );

        return rest_ensure_response([
            'success' => true,
            'data'    => __( 'Content rewritten successfully.', 'antimanual' ),
        ]);
    }

    /**
     * Generate a featured image for a post using AI.
     *
     * Uses the post title and a content summary to build an image prompt,
     * generates the image via AIProvider, sideloads it into the media library,
     * and sets it as the post thumbnail.
     *
     * @param \WP_REST_Request $request The REST request.
     * @return \WP_REST_Response|\WP_Error The REST response.
     */
    public function generate_featured_image( $request ) {
        if ( atml_is_bulk_rewrite_limit_exceeded() ) {
            return new \WP_Error(
                'monthly_limit_exceeded',
                __( 'You have reached your monthly limit of 100 bulk rewrite actions. Upgrade to Pro for unlimited actions.', 'antimanual' )
            );
        }

        $payload = json_decode( $request->get_body(), true );
        $payload = is_array( $payload ) ? $payload : [];

        $post_id                = intval( $payload['postId'] ?? 0 );
        $overwrite              = filter_var( $payload['overwrite'] ?? false, FILTER_VALIDATE_BOOLEAN );
        $use_post_title_in_image = filter_var( $payload['usePostTitleInImage'] ?? true, FILTER_VALIDATE_BOOLEAN );

        if ( ! $post_id ) {
            return rest_ensure_response([
                'success' => false,
                'message' => __( 'Post ID is required.', 'antimanual' ),
            ]);
        }

        $post = get_post( $post_id );

        if ( ! $post ) {
            return rest_ensure_response([
                'success' => false,
                'message' => __( 'Post not found.', 'antimanual' ),
            ]);
        }

        if ( ! current_user_can( 'edit_post', $post_id ) ) {
            return rest_ensure_response([
                'success' => false,
                'message' => __( 'Unauthorized', 'antimanual' ),
            ]);
        }

        // Skip posts that already have a thumbnail unless overwrite is enabled.
        if ( ! $overwrite && has_post_thumbnail( $post_id ) ) {
            return rest_ensure_response([
                'success' => true,
                'data'    => __( 'Post already has a featured image. Skipped.', 'antimanual' ),
            ]);
        }

        $title   = trim( wp_strip_all_tags( $post->post_title ) );
        $content = trim( wp_strip_all_tags( $post->post_content ) );

        // Build a short content summary (first ~200 words) for context.
        $content_words = preg_split( '/\s+/', $content, 201, PREG_SPLIT_NO_EMPTY );
        $summary       = implode( ' ', array_slice( $content_words ?: [], 0, 200 ) );

        // Ask AI to generate a concise image generation prompt.
        $instructions = "You are a visual designer. Given a post title and content summary, "
            . "write a single detailed image generation prompt (30-60 words) for a professional featured image. "
            . "Describe the scene, style, lighting, composition, and mood. "
            . "Do not include text overlays or watermarks in the design. "
            . "Return ONLY the image prompt, no explanations or labels.";

        $user_msg = "Post Title: " . $title . "\n\nContent Summary:\n" . $summary;

        $messages = [
            [
                'role'    => 'system',
                'content' => $instructions,
            ],
            [
                'role'    => 'user',
                'content' => $user_msg,
            ],
        ];

        $image_prompt = AIProvider::get_reply( $messages, '', '', 200 );

        if ( ! is_string( $image_prompt ) || '' === trim( $image_prompt ) ) {
            // Fallback: use the post title directly as the image prompt.
            $image_prompt = sprintf(
                'Create a clean, professional featured image for this article: %s',
                $title ?: __( 'Untitled Post', 'antimanual' )
            );
        }

        $image_prompt = trim( wp_strip_all_tags( $image_prompt ) );
        $image_prompt = trim( $image_prompt, "\"'`" );

        // Append title text instruction when enabled.
        if ( $use_post_title_in_image && '' !== $title ) {
            $short_title_text       = PostGenerator::build_featured_image_title_text( $title );
            $title_text_instruction = sprintf(
                'The image MUST include short, meaningful title text that is derived from the post title but NOT the exact full post title. Use this short text in the image: "%s". Keep the typography clear, legible, and high-contrast.',
                $short_title_text
            );
            $image_prompt = sprintf(
                '%1$s %2$s',
                $image_prompt,
                $title_text_instruction
            );
        }

        // Generate the image.
        $image_url = AIProvider::generate_image( $image_prompt );

        if ( is_wp_error( $image_url ) ) {
            return rest_ensure_response([
                'success' => false,
                'message' => $image_url->get_error_message(),
            ]);
        }

        // Sideload the image into the media library.
        $image_id = PostGenerator::sideload_image_public( $image_url, $post_id, $title );

        if ( is_wp_error( $image_id ) ) {
            return rest_ensure_response([
                'success' => false,
                'message' => $image_id->get_error_message(),
            ]);
        }

        // Set as post thumbnail.
        set_post_thumbnail( $post_id, $image_id );

        if ( ! atml_is_pro() ) {
            \Antimanual\UsageTracker::increment( 'bulk_rewrite' );
        }

        return rest_ensure_response([
            'success' => true,
            'data'    => __( 'Featured image generated successfully.', 'antimanual' ),
        ]);
    }
}
