<?php

namespace WeDevs\Wpuf\Pro\AI_Review;

/**
 * AI Review Helper - Shared utility methods
 *
 * @since 4.2.5
 */
class Helper {

    /**
     * Save review result to post meta
     *
     * @since 4.2.5
     * @param int $post_id Post ID
     * @param array $result Review result
     * @param string $method Review method
     */
    public static function save_review_result( $post_id, $result, $method = 'immediate' ) {
        $review_data = [
            'status'        => $result['status'],
            'summary'       => $result['summary'],
            'reviewed_at'   => time(),
            'review_method' => $method,
        ];

        update_post_meta( $post_id, 'wpuf_ai_post_review', $review_data );
        update_post_meta( $post_id, 'wpuf_ai_review_status', $result['status'] );
    }

    /**
     * Save pending review status
     *
     * @since 4.2.5
     * @param int $post_id Post ID
     */
    public static function save_pending_review( $post_id ) {
        $review_data = [
            'status'        => 'pending',
            'summary'       => 'Review scheduled for background processing',
            'reviewed_at'   => time(),
            'review_method' => 'scheduled',
        ];

        update_post_meta( $post_id, 'wpuf_ai_post_review', $review_data );
        update_post_meta( $post_id, 'wpuf_ai_review_status', $review_data['status'] );
    }

    /**
     * Save in progress review status
     *
     * @since 4.2.5
     * @param int $post_id Post ID
     */
    public static function save_in_progress_review( $post_id ) {
        $review_data = [
            'status'        => 'in_progress',
            'summary'       => 'Review in progress',
            'reviewed_at'   => time(),
            'review_method' => 'action_scheduler',
        ];

        update_post_meta( $post_id, 'wpuf_ai_post_review', $review_data );
        update_post_meta( $post_id, 'wpuf_ai_review_status', $review_data['status'] );
    }

    /**
     * Save failed review
     *
     * @since 4.2.5
     * @param int $post_id Post ID
     * @param string $error Error message
     */
    public static function save_failed_review( $post_id, $error ) {
        $review_data = [
            'status'        => 'failed',
            'summary'       => 'Review failed: ' . $error,
            'reviewed_at'   => time(),
            'review_method' => 'immediate',
        ];

        update_post_meta( $post_id, 'wpuf_ai_post_review', $review_data );
        update_post_meta( $post_id, 'wpuf_ai_review_status', $review_data['status'] );
    }

    /**
     * Make HTTP API call with retry logic
     *
     * @since 4.2.5
     * @param string $url API URL
     * @param array $args Request arguments
     * @param array $config Configuration options
     * @return array Response data
     * @throws \Exception
     */
    public static function make_api_call( $url, $args, $config = [] ) {
        $max_retries = $config['max_retries'] ?? 3;
        $retry_delay = $config['retry_delay'] ?? 1;
        $timeout = $config['timeout'] ?? 30;

        for ( $attempt = 1; $attempt <= $max_retries; $attempt++ ) {
            $response = wp_remote_post( $url, array_merge( $args, [ 'timeout' => $timeout ] ) );

            if ( is_wp_error( $response ) ) {
                $error_code = $response->get_error_code();
                if ( $attempt < $max_retries && in_array( $error_code, [ 'http_request_failed', 'timeout', 'connection_failed' ] ) ) {
                    sleep( $retry_delay * $attempt );
                    continue;
                }
                throw new \Exception( 'API error: ' . $response->get_error_message() );
            }

            $status_code = wp_remote_retrieve_response_code( $response );

            // Handle rate limiting
            if ( $status_code === 429 ) {
                $body = wp_remote_retrieve_body( $response );
                $decoded = json_decode( $body, true );

                if ( $attempt < $max_retries ) {
                    $retry_after = isset( $decoded['error']['retry_after'] ) ? (int) $decoded['error']['retry_after'] : $retry_delay * $attempt;
                    sleep( $retry_after );
                    continue;
                }
                throw new \Exception( 'API rate limit exceeded. Please try again later.' );
            }

            // Handle server errors
            if ( $status_code >= 500 && $attempt < $max_retries ) {
                sleep( $retry_delay * $attempt );
                continue;
            }

            return $response;
        }

        throw new \Exception( 'API failed after ' . $max_retries . ' attempts' );
    }

    /**
     * Extract field types from form fields
     *
     * @since 4.2.5
     * @param array $form_fields Form fields
     * @return array Array containing post_vars, taxonomy_vars, meta_vars
     */
    public static function extract_field_types( $form_fields ) {
        $post_vars = [];
        $taxonomy_vars = [];
        $meta_vars = [];

        foreach ( $form_fields as $field ) {
            if ( ! isset( $field['name'] ) ) {
                continue;
            }

            $field_type = $field['input_type'] ?? 'text';

            // Categorize fields based on type
            if ( in_array( $field_type, [ 'post_title', 'post_content', 'post_excerpt', 'featured_image' ] ) ) {
                $post_vars[] = $field;
            } elseif ( in_array( $field_type, [ 'taxonomy' ] ) ) {
                $taxonomy_vars[] = $field;
            } else {
                $meta_vars[] = $field;
            }
        }

        return [ $post_vars, $taxonomy_vars, $meta_vars ];
    }
}
