<?php

/**
 * API endpoint for restarting failed or cancelled article generations
 * 
 * @package ContentCraftAI
 */

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

/**
 * Handles restarting a failed or cancelled article generation
 * 
 * @param WP_REST_Request $request The request object
 * @return WP_REST_Response Response object
 */
function content_craft_ai_restart_generation($request)
{
  // Get queue ID from the request
  $queue_id = $request->get_param('queueId');

  if (empty($queue_id)) {
    return new WP_REST_Response([
      'success' => false,
      'message' => 'Queue ID is required'
    ], 400);
  }

  // Get article status controller
  $article_status_controller = new ContentCraftAI_ArticleStatusController();

  // Get the generation to check if it's failed or cancelled
  $generation = $article_status_controller->get_generation_by_queue_id($queue_id);

  if (!$generation) {
    return new WP_REST_Response([
      'success' => false,
      'message' => 'Generation not found'
    ], 404);
  }

  // Only allow restart for failed or cancelled generations
  if ($generation['status'] !== 'failed' && $generation['status'] !== 'cancelled') {
    return new WP_REST_Response([
      'success' => false,
      'message' => 'Only failed or cancelled generations can be restarted'
    ], 400);
  }

  // Get current parameters and add restart flag
  $current_params = !empty($generation['parameters']) ? $generation['parameters'] : [];
  $updated_params = $current_params;
  $updated_params['restarted'] = true;
  $updated_params['restartedAt'] = gmdate('Y-m-d H:i:s');

  // Check if this was a previously scheduled article
  $was_scheduled = false;

  // Check for scheduled indicators in parameters or DB fields
  if (
    (isset($current_params['scheduleDateTime']) && !empty($current_params['scheduleDateTime'])) ||
    !empty($generation['scheduled_time']) ||
    !empty($generation['is_scheduled'])
  ) {
    $was_scheduled = true;
  }

  // Update the parameters
  $article_status_controller->update_generation_parameters($queue_id, $updated_params);

  // Check if this article had an API queue ID
  $has_api_queue_id = isset($current_params['apiQueueId']) && !empty($current_params['apiQueueId']);
  $api_queue_id = $has_api_queue_id ? $current_params['apiQueueId'] : $queue_id;

  // For previously scheduled articles without API queue ID, just update status in database
  if ($was_scheduled && !$has_api_queue_id) {
    // Update the status to scheduled to restart the scheduled generation
    $result = $article_status_controller->update_generation_status($queue_id, 'scheduled');

    if ($result) {
      return new WP_REST_Response([
        'success' => true,
        'message' => 'Scheduled generation restarted successfully',
        'data' => [
          'queue_id' => $queue_id,
          'status' => 'scheduled'
        ]
      ], 200);
    } else {
      return new WP_REST_Response([
        'success' => false,
        'message' => 'Failed to restart scheduled generation'
      ], 500);
    }
  }

  // For articles with API queue ID, call the external API to restart
  if ($has_api_queue_id) {
    // Get API key
    $api_key = get_option('content_craft_ai_api_key');

    if (empty($api_key)) {
      return new WP_REST_Response([
        'success' => false,
        'message' => 'API key not found. Please check your authentication.'
      ], 401);
    }

    // Prepare API request
    $api_url = defined('CONTENT_CRAFT_AI_EXTERNAL_API') ? CONTENT_CRAFT_AI_EXTERNAL_API : '';

    if (empty($api_url)) {
      return new WP_REST_Response([
        'success' => false,
        'message' => 'External API URL not defined'
      ], 500);
    }

    // Set up headers following the pattern from image-services.php
    $headers = [
      'Content-Type' => 'application/json',
      'x-api-key' => $api_key,
      'x-wp-domain' => wp_parse_url(get_site_url(), PHP_URL_HOST)
    ];

    // Set up request arguments
    $request_args = [
      'headers' => $headers,
      'method' => 'POST',
      'timeout' => 120
    ];

    // Make the API request to restart the generation
    $response = wp_remote_request(
      $api_url . '/articles/queue/' . $api_queue_id . '/restart',
      $request_args
    );

    // Handle API response
    if (is_wp_error($response)) {
      return new WP_REST_Response([
        'success' => false,
        'message' => 'Failed to restart generation: ' . $response->get_error_message()
      ], 500);
    }

    $status_code = wp_remote_retrieve_response_code($response);
    $body = wp_remote_retrieve_body($response);
    $data = json_decode($body, true);

    // Process successful API response
    if ($status_code >= 200 && $status_code < 300 && !empty($data['success'])) {
      // Update the original generation to reference the new queue ID if provided
      if (!empty($data['data']['newQueueId'])) {
        $updated_params['oldQueueId'] = $api_queue_id;
        $updated_params['apiQueueId'] = $data['data']['newQueueId'];
        $updated_params['newQueueId'] = $data['data']['newQueueId'];

        // Update parameters with new queue ID
        $article_status_controller->update_generation_parameters($queue_id, $updated_params);
      }

      // Update status to 'pending'
      $article_status_controller->update_generation_status($queue_id, 'pending');

      return new WP_REST_Response([
        'success' => true,
        'message' => 'Generation restarted successfully',
        'data' => $data
      ], 200);
    } else {
      // If API call failed, return the error
      return new WP_REST_Response([
        'success' => false,
        'message' => 'Failed to restart generation with the external API',
        'api_response' => [
          'status' => $status_code,
          'data' => $data
        ]
      ], 500);
    }
  }

  // Fallback for articles without API queue ID that aren't scheduled
  // Just update status to pending locally
  $result = $article_status_controller->update_generation_status($queue_id, 'pending');

  if ($result) {
    return new WP_REST_Response([
      'success' => true,
      'message' => 'Generation restarted successfully',
      'data' => [
        'queue_id' => $queue_id,
        'status' => 'pending'
      ]
    ], 200);
  } else {
    return new WP_REST_Response([
      'success' => false,
      'message' => 'Failed to restart generation'
    ], 500);
  }
}
