<?php
/**
 * ==========================
 * 🔐 IGNY8 FILE RULE HEADER
 * ==========================
 * @file         : runware-api.php
 * @location     : /ai/runware-api.php
 * @type         : AI Integration
 * @scope        : Global
 * @allowed      : Runware API calls, image generation, AI processing
 * @reusability  : Globally Reusable
 * @notes        : Runware image generation API integration
 */

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

/**
 * Generate image using Runware API
 * 
 * @param string $prompt The image generation prompt
 * @param string $model The Runware model to use (default: gen3a_turbo)
 * @return array|WP_Error Response data or error
 */
function igny8_runway_generate_image($prompt, $model = 'gen3a_turbo') {
    $api_key = get_option('igny8_runware_api_key', '');
    
    if (empty($api_key)) {
        return new WP_Error('no_api_key', 'Runware API key not configured');
    }
    
    $url = 'https://api.runwayml.com/v1/image/generations';
    
    $headers = [
        'Authorization' => 'Bearer ' . $api_key,
        'Content-Type' => 'application/json',
    ];
    
    $body = [
        'model' => $model,
        'prompt' => $prompt,
        'size' => '1024x1024',
        'quality' => 'standard',
        'n' => 1
    ];
    
    $args = [
        'method' => 'POST',
        'headers' => $headers,
        'body' => json_encode($body),
        'timeout' => 60,
    ];
    
    $response = wp_remote_post($url, $args);
    
    if (is_wp_error($response)) {
        igny8_log_ai_event('runway_api_error', 'error', [
            'message' => $response->get_error_message(),
            'prompt' => $prompt,
            'model' => $model
        ]);
        return $response;
    }
    
    $response_code = wp_remote_retrieve_response_code($response);
    $response_body = wp_remote_retrieve_body($response);
    $response_data = json_decode($response_body, true);
    
    if ($response_code !== 200) {
        $error_message = isset($response_data['error']['message']) ? $response_data['error']['message'] : 'Unknown error';
        igny8_log_ai_event('runway_api_error', 'error', [
            'code' => $response_code,
            'message' => $error_message,
            'prompt' => $prompt,
            'model' => $model
        ]);
        return new WP_Error('api_error', $error_message);
    }
    
    // Log successful API call
    igny8_log_ai_event('runway_api_success', 'success', [
        'model' => $model,
        'prompt_length' => strlen($prompt),
        'cost' => 0.009, // Runware pricing
        'service' => 'runware'
    ]);
    
    return $response_data;
}

/**
 * Download and save image from Runware response
 * 
 * @param array $response_data The API response data
 * @param string $filename The desired filename
 * @return string|WP_Error Saved file path or error
 */
function igny8_runway_save_image($response_data, $filename) {
    if (!isset($response_data['data'][0]['url'])) {
        return new WP_Error('no_image_url', 'No image URL in response');
    }
    
    $image_url = $response_data['data'][0]['url'];
    
    // Create uploads directory
    $upload_dir = wp_upload_dir();
    $igny8_dir = $upload_dir['basedir'] . '/igny8-ai-images/';
    
    if (!file_exists($igny8_dir)) {
        wp_mkdir_p($igny8_dir);
    }
    
    // Download image
    $image_response = wp_remote_get($image_url);
    
    if (is_wp_error($image_response)) {
        return $image_response;
    }
    
    $image_data = wp_remote_retrieve_body($image_response);
    $file_path = $igny8_dir . $filename;
    
    $saved = file_put_contents($file_path, $image_data);
    
    if ($saved === false) {
        return new WP_Error('save_failed', 'Failed to save image file');
    }
    
    return $file_path;
}

/**
 * Test Runware API connection
 * 
 * @return array Test result
 */
function igny8_test_runway_connection() {
    $test_prompt = 'A simple test image: a red circle on white background';
    
    $response = igny8_runway_generate_image($test_prompt);
    
    if (is_wp_error($response)) {
        return [
            'success' => false,
            'message' => $response->get_error_message(),
            'details' => 'Runware API connection failed'
        ];
    }
    
    return [
        'success' => true,
        'message' => 'Runware API connection successful',
        'details' => 'Test image generation completed successfully'
    ];
}

/**
 * Get available Runware models
 * 
 * @return array Available models
 */
function igny8_get_runway_models() {
    return [
        'gen3a_turbo' => [
            'name' => 'Gen-3 Alpha Turbo',
            'description' => 'Fast, high-quality image generation',
            'cost' => 0.055
        ],
        'gen3a' => [
            'name' => 'Gen-3 Alpha',
            'description' => 'Standard quality image generation',
            'cost' => 0.055
        ]
    ];
}

/**
 * Log AI event for Runway API
 * 
 * @param string $event Event type
 * @param string $status Success/error status
 * @param array $context Additional context data
 */
function igny8_log_runway_event($event, $status, $context = []) {
    igny8_log_ai_event($event, $status, array_merge($context, [
        'service' => 'runware',
        'timestamp' => current_time('mysql')
    ]));
}
