<?php
defined('ABSPATH') || exit;

/**
 * Smart file inspection endpoint that only requires the file path
 * 
 * @param WP_REST_Request $request Request object
 * @return WP_REST_Response|WP_Error Response object
 */
function wpsec_smart_inspect_file_endpoint($request) {
    // Debug logging
    wpsec_log('Smart file inspection endpoint called', 'info');
    
    // Validate API key
    if (!wpsec_validate_api_key()) {
        wpsec_log('API key validation failed for smart file inspection', 'error');
        return new WP_Error(
            'rest_forbidden',
            'Sorry, you are not allowed to do that.',
            array('status' => 401)
        );
    }

    // Get file path parameter
    $file_path = $request->get_param('file_path');
    
    if (empty($file_path)) {
        wpsec_log('Missing required parameter: file_path', 'error');
        return new WP_Error(
            'missing_parameter',
            'Missing required parameter: file_path',
            array('status' => 400)
        );
    }
    
    // Normalize the file path
    $normalized_path = wpsec_normalize_scan_path($file_path);
    wpsec_log('Original path: ' . $file_path, 'info');
    wpsec_log('Normalized path: ' . $normalized_path, 'info');

    // Security checks - use remote inspection mode for API endpoints
    if (!wpsec_validate_file_path($normalized_path, true)) {
        wpsec_log('Invalid or unsafe file path: ' . $normalized_path, 'error');
        return new WP_Error(
            'invalid_file_path',
            'Invalid or unsafe file path',
            array('status' => 400)
        );
    }
    
    // Ensure file exists
    if (!file_exists($normalized_path)) {
        wpsec_log('File not found: ' . $normalized_path, 'error');
        return new WP_Error(
            'file_not_found',
            'File not found',
            array('status' => 404)
        );
    }
    
    // Get the file detections from the latest scan results
    $file_detections = wpsec_get_file_detections_from_latest_scan($file_path);
    
    if (empty($file_detections)) {
        wpsec_log('No detections found in recent scans for: ' . $file_path, 'warning');
    }
    
    // Get comprehensive file information with code snippets for all detection types
    $file_info = wpsec_get_comprehensive_file_info($normalized_path, $file_detections);
    
    if (is_wp_error($file_info)) {
        wpsec_log('File inspection failed: ' . $file_info->get_error_message(), 'error');
        return $file_info;
    }
    
    wpsec_log('Smart file inspection completed successfully: ' . $normalized_path, 'info');
    
    return rest_ensure_response([
        'status' => 'success',
        'file_info' => $file_info
    ]);
}

/**
 * Get detailed information about a file, including code snippets
 * 
 * @param WP_REST_Request $request Request object
 * @return WP_REST_Response|WP_Error Response object
 */
function wpsec_inspect_file_endpoint($request) {
    // Debug logging
    wpsec_log('File inspection endpoint called', 'info');
    
    // Validate API key (double check)
    if (!wpsec_validate_api_key()) {
        wpsec_log('API key validation failed for file inspection', 'error');
        return new WP_Error(
            'rest_forbidden',
            'Sorry, you are not allowed to do that.',
            array('status' => 401)
        );
    }

    // Get parameters
    $file_path = $request->get_param('file_path');
    $detection_type = $request->get_param('detection_type');
    $pattern = $request->get_param('pattern');
    
    if (empty($file_path)) {
        wpsec_log('Missing required parameter: file_path', 'error');
        return new WP_Error(
            'missing_parameter',
            'Missing required parameter: file_path',
            array('status' => 400)
        );
    }
    
    // Create a simplified detection object with just the type and pattern
    $detection = [
        'type' => $detection_type ?: 'unknown',
        'pattern' => $pattern
    ];
    
    // Normalize the file path to handle different server configurations
    $normalized_path = wpsec_normalize_scan_path($file_path);
    wpsec_log('Original path: ' . $file_path, 'info');
    wpsec_log('Normalized path: ' . $normalized_path, 'info');

    // Security checks - use remote inspection mode for API endpoints
    if (!wpsec_validate_file_path($normalized_path, true)) {
        wpsec_log('Invalid or unsafe file path: ' . $normalized_path, 'error');
        return new WP_Error(
            'invalid_file_path',
            'Invalid or unsafe file path',
            array('status' => 400)
        );
    }
    
    // Ensure file exists
    if (!file_exists($normalized_path)) {
        wpsec_log('File not found: ' . $normalized_path, 'error');
        return new WP_Error(
            'file_not_found',
            'File not found',
            array('status' => 404)
        );
    }
    
    // Get file information with code snippets
    $file_info = wpsec_get_malware_file_info($normalized_path, $detection);
    
    if (is_wp_error($file_info)) {
        wpsec_log('File inspection failed: ' . $file_info->get_error_message(), 'error');
        return $file_info;
    }
    
    wpsec_log('File inspection completed successfully: ' . $normalized_path, 'info');
    
    return rest_ensure_response([
        'status' => 'success',
        'file_info' => $file_info
    ]);
}

/**
 * Get detailed information about multiple files from scan results
 * 
 * @param WP_REST_Request $request Request object
 * @return WP_REST_Response|WP_Error Response object
 */
function wpsec_inspect_scan_results_endpoint($request) {
    // Debug logging
    wpsec_log('Scan results inspection endpoint called', 'info');
    
    // Validate API key (double check)
    if (!wpsec_validate_api_key()) {
        wpsec_log('API key validation failed for scan results inspection', 'error');
        return new WP_Error(
            'rest_forbidden',
            'Sorry, you are not allowed to do that.',
            array('status' => 401)
        );
    }

    // Get parameters
    $scan_results = $request->get_param('scan_results');
    $limit = $request->get_param('limit') ? intval($request->get_param('limit')) : 5;
    
    if (empty($scan_results) || !isset($scan_results['infected_files']) || !is_array($scan_results['infected_files'])) {
        wpsec_log('Missing or invalid required parameter: scan_results', 'error');
        return new WP_Error(
            'missing_parameter',
            'Missing or invalid required parameter: scan_results',
            array('status' => 400)
        );
    }
    
    // Process each infected file (up to the limit)
    $processed_files = [];
    $count = 0;
    
    foreach ($scan_results['infected_files'] as $infected_file) {
        if ($count >= $limit) {
            break;
        }
        
        $file_path = isset($infected_file['file_path']) ? $infected_file['file_path'] : '';
        if (empty($file_path)) {
            continue;
        }
        
        // Create a simplified detection object with just the type and pattern
        $detection_type = !empty($infected_file['detections']) ? $infected_file['detections'][0]['type'] : 'unknown';
        $pattern = !empty($infected_file['detections']) ? $infected_file['detections'][0]['pattern'] : null;
        
        $detection = [
            'type' => $detection_type,
            'pattern' => $pattern
        ];
        
        // Normalize the file path
        $normalized_path = wpsec_normalize_scan_path($file_path);
        
        // Skip if file doesn't exist or isn't valid
        if (!file_exists($normalized_path) || !wpsec_validate_file_path($normalized_path)) {
            continue;
        }
        
        // Get file information with code snippets
        $file_info = wpsec_get_malware_file_info($normalized_path, $detection);
        
        if (!is_wp_error($file_info)) {
            $processed_files[] = [
                'file_path' => $file_path,
                'normalized_path' => $normalized_path,
                'threat_score' => isset($infected_file['threat_score']) ? $infected_file['threat_score'] : 0,
                'confidence' => isset($infected_file['confidence']) ? $infected_file['confidence'] : 0,
                'file_info' => $file_info
            ];
            
            $count++;
        }
    }
    
    wpsec_log('Scan results inspection completed: processed ' . count($processed_files) . ' files', 'info');
    
    return rest_ensure_response([
        'status' => 'success',
        'processed_count' => count($processed_files),
        'total_infected' => count($scan_results['infected_files']),
        'files' => $processed_files
    ]);
}
