<?php

if (!defined('ABSPATH')) {
    exit;
}

/**
 * This file depends on WordPress core functionality.
 * The following constants and types are defined by WordPress and will be available at runtime:
 * - CONTENT_CRAFT_AI_PLUGIN_PATH: Plugin path constant defined in the main plugin file
 * - WP_REST_Response: WordPress REST API response class
 */

// Include our new controller
require_once CONTENT_CRAFT_AI_PLUGIN_PATH . 'app/controllers/article-generator/ArticleGenerationController.php';

/**
 * Handle single article generation request
 * 
 * @param WP_REST_Request $request The request object
 * @return WP_REST_Response The response object
 */
function content_craft_ai_handle_single_article_generation($request)
{
    try {
        $params = $request->get_json_params();

        // Get the controller instance
        $controller = ContentCraftAI_ArticleGenerationController::get_instance();

        // Use the controller to generate a single article
        $result = $controller->generate_single_article($params);

        if ($result['success']) {
            return new WP_REST_Response([
                'success' => true,
                'message' => 'Article generation started successfully',
                'data' => $result['data']
            ]);
        } else {
            return new WP_REST_Response([
                'success' => false,
                'message' => $result['message']
            ], $result['code'] ?? 500);
        }
    } catch (Exception $e) {
        return new WP_REST_Response([
            'success' => false,
            'message' => $e->getMessage()
        ], 500);
    }
}

/**
 * Make a direct call to the external API to generate an article
 * 
 * @param array $article_data Article generation parameters
 * @return array Response from the API
 */
function content_craft_ai_api_generate_article($article_data)
{
    // Build API URL from constant or fallback to default
    $api_url = defined('CONTENT_CRAFT_AI_EXTERNAL_API')
        ? CONTENT_CRAFT_AI_EXTERNAL_API
        : '';

    if (empty($api_url)) {
        return [
            'success' => false,
            'message' => 'API URL not configured'
        ];
    }

    // Get internal links if feature is enabled
    $user_settings = get_option('content_craft_ai_user_settings', []);
    $smart_linking_enabled = $user_settings['smartLinkingEnabled'] ?? false;
    $internal_links = [];

    if ($smart_linking_enabled && function_exists('content_craft_ai_get_internal_links_for_api')) {
        $focus_keyword = $article_data['focusKeyword'] ?? '';
        $category_id = $article_data['category'] ?? null;

        // Get internal links data for the article
        $internal_links = content_craft_ai_get_internal_links_for_api($focus_keyword, $category_id);
    }

    // Format data for the API
    $request_body = [
        'title' => $article_data['title'],
        'wordCount' => $article_data['wordCount'],
        'focusKeyword' => $article_data['focusKeyword'],
        'tagCount' => $article_data['tagCount'] ?? 5,
        'aiModel' => $article_data['aiModel'] ?? 'gpt-4o-mini',
        'imageService' => $article_data['imageService'] ?? 'pexels',
        'includeImages' => $article_data['includeImages'] ?? true,
        'setFeaturedImage' => $article_data['setFeaturedImage'] ?? true,
        'imageKeywords' => $article_data['imageKeywords'] ?? $article_data['focusKeyword'],
        'postStatus' => $article_data['postStatus'] ?? 'draft',
        'language' => $article_data['language'] ?? 'en',
        'internalLinks' => $internal_links, // Add internal links data to the request
    ];

    // Get SEO plugin from settings
    $request_body['seoPlugin'] = $user_settings['seoPlugin'] ?? 'none';

    // Get API key
    $api_key = get_option('content_craft_ai_api_key', '');

    // Prepare headers
    $headers = [
        'Content-Type' => 'application/json',
        'x-api-key' => $api_key,
    ];

    // Prepare request args
    $request_args = [
        'headers' => $headers,
        'body' => json_encode($request_body, JSON_UNESCAPED_UNICODE),
        'timeout' => 120
    ];

    // Add domain header - sanitize and unslash HTTP_HOST
    $domain = isset($_SERVER['HTTP_HOST']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_HOST'])) : site_url();
    $request_args['headers']['x-wp-domain'] = $domain;

    // Make API request
    $response = wp_remote_post($api_url . '/articles/generate', $request_args);

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

    // Get response code and body
    $response_code = wp_remote_retrieve_response_code($response);
    $body = json_decode(wp_remote_retrieve_body($response), true);

    // Check for error response (anything other than 200-299)
    if ($response_code < 200 || $response_code >= 300) {
        // Include HTTP status code in the response
        return [
            'success' => false,
            'message' => $body['message'] ?? 'API error (code: ' . $response_code . ')',
            'code' => $response_code, // Use actual HTTP status code
            'errorCode' => $body['code'] ?? null // Include API error code if available
        ];
    }

    if (!$body) {
        return [
            'success' => false,
            'message' => 'Invalid API response'
        ];
    }

    return $body;
}

/**
 * Validate article parameters without generating
 * 
 * @param array $params Article parameters to validate
 * @param bool $is_bulk Whether this is a bulk validation request
 * @return array Response with validation result
 */
function content_craft_ai_api_validate_article($params, $is_bulk = false)
{
    // Build API URL from constant or fallback to default
    $api_url = defined('CONTENT_CRAFT_AI_EXTERNAL_API')
        ? CONTENT_CRAFT_AI_EXTERNAL_API
        : '';

    if (empty($api_url)) {
        return [
            'success' => false,
            'message' => 'API URL not configured'
        ];
    }

    // Get API key
    $api_key = get_option('content_craft_ai_api_key', '');

    // Prepare headers
    $headers = [
        'Content-Type' => 'application/json',
        'x-api-key' => $api_key,
    ];

    // Add domain header - sanitize and unslash HTTP_HOST
    $domain = isset($_SERVER['HTTP_HOST']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_HOST'])) : site_url();
    $headers['x-wp-domain'] = $domain;

    // Format the request body based on whether it's a bulk request or not
    $request_body = $is_bulk
        ? ['bulk' => true, 'articles' => $params]
        : $params;

    // Prepare request args
    $request_args = [
        'headers' => $headers,
        'body' => json_encode($request_body, JSON_UNESCAPED_UNICODE),
        'timeout' => 60
    ];

    // Make API request to validation endpoint
    $response = wp_remote_post($api_url . '/articles/validate', $request_args);

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

    // Get response code and body
    $response_code = wp_remote_retrieve_response_code($response);
    $response_body = wp_remote_retrieve_body($response);
    $body = json_decode($response_body, true);

    // Check for error response (anything other than 200-299)
    if ($response_code < 200 || $response_code >= 300) {
        // Keep the results array if present in the error response
        $response_data = [
            'success' => false,
            'message' => $body['message'] ?? 'API error (code: ' . $response_code . ')',
            'code' => $response_code,
        ];

        // Add errors array if present
        if (isset($body['errors'])) {
            $response_data['errors'] = $body['errors'];
        }

        // Add results array if present (important for bulk validation)
        if (isset($body['results'])) {
            $response_data['results'] = $body['results'];
        }

        // If this is a bulk validation with no results array but has a validation error,
        // create a synthetic results array based on the request
        if (
            $is_bulk && !isset($body['results']) && $response_code === 403 &&
            (strpos($body['message'] ?? '', 'validation') !== false ||
                strpos($body['message'] ?? '', 'limit') !== false)
        ) {

            // Create synthetic results based on the request articles
            $synthetic_results = [];
            foreach ($params as $index => $article) {
                $title = $article['title'] ?? 'Untitled article ' . ($index + 1);
                $synthetic_results[] = [
                    'valid' => false,
                    'article' => $title,
                    'errors' => [
                        [
                            'param' => 'unknown',
                            'message' => $body['message'] ?? 'Validation failed',
                        ]
                    ]
                ];
            }

            $response_data['results'] = $synthetic_results;
        }

        return $response_data;
    }

    if (!$body) {
        return [
            'success' => false,
            'message' => 'Invalid API response',
            'code' => 500
        ];
    }

    return $body;
}
