isLoggedIn() || !$auth->isAdmin()) { die("Admin access required"); } header('Content-Type: text/html; charset=utf-8'); echo "

OptimAIze Fix & Test Script

"; echo ""; $db = Database::getInstance(); if ($_SERVER['REQUEST_METHOD'] == 'POST') { $action = $_POST['action'] ?? ''; switch ($action) { case 'test_gpt': echo "

Testing GPT Connection

"; testGPTConnection(); break; case 'reset_analysis': echo "

Resetting Analysis State

"; resetAnalysisState(); break; case 'start_analysis': echo "

Starting Analysis

"; startAnalysis(); break; case 'check_background': echo "

Checking Background Process

"; checkBackgroundProcess(); break; } } echo "

Current Status

"; displayCurrentStatus(); echo "

Available Actions

"; echo "
"; echo ""; echo ""; echo ""; echo ""; echo "
"; echo "
"; echo "

Recommended Steps:

"; echo "
    "; echo "
  1. Test GPT Connection - Verify GPT API is working
  2. "; echo "
  3. Reset Analysis State - Clear stuck state
  4. "; echo "
  5. Start Analysis - Begin processing combinations
  6. "; echo "
  7. Check Background Process - Monitor progress
  8. "; echo "
"; echo "
"; function displayCurrentStatus() { global $db; // Check GptHelper class try { require_once 'includes/GptHelper.php'; if (class_exists('GptHelper')) { echo "
✅ GptHelper class loaded successfully
"; } else { echo "
❌ GptHelper class not found
"; } } catch (Exception $e) { echo "
❌ Error loading GptHelper: " . $e->getMessage() . "
"; } // Check analysis state $stateResult = $db->query("SELECT * FROM optimization_analysis_state ORDER BY id DESC LIMIT 1"); if ($stateResult && $stateResult->num_rows > 0) { $state = $stateResult->fetch_assoc(); $statusClass = $state['is_running'] ? 'warning' : 'info'; $statusText = $state['is_running'] ? 'RUNNING' : 'STOPPED'; echo "
Analysis Status: $statusText
"; echo "
Progress: " . number_format($state['processed_combinations']) . " / " . number_format($state['total_combinations']) . " combinations
"; } // Check recent progress $recentCount = $db->query("SELECT COUNT(*) as count FROM panel_directives WHERE llm_checked = 1 AND updated_at > DATE_SUB(NOW(), INTERVAL 5 MINUTE)")->fetch_assoc()['count']; if ($recentCount > 0) { echo "
✅ Recent activity: $recentCount combinations processed in last 5 minutes
"; } else { echo "
⚠️ No recent activity detected
"; } } function testGPTConnection() { try { require_once 'includes/GptHelper.php'; if (!class_exists('GptHelper')) { throw new Exception("GptHelper class not found"); } echo "
✅ GptHelper class loaded
"; // Test simple GPT request $testMessages = [ [ 'role' => 'user', 'content' => 'Respond with exactly: "TEST SUCCESSFUL"' ] ]; echo "
📡 Sending test request to OpenAI...
"; $response = GptHelper::makeRequest($testMessages, 'gpt-4', 0.3); if ($response['success']) { echo "
✅ GPT connection successful!
"; echo "
Response: " . htmlspecialchars($response['response']) . "
"; // Test the specific analysis function echo "
🔍 Testing demographic analysis...
"; $analysisResult = GptHelper::analyzeCombination('Age', '5-12 years', 'Marital Status', 'Married'); if ($analysisResult['is_impossible']) { echo "
✅ Analysis function working correctly (correctly identified impossible combination)
"; } else { echo "
⚠️ Analysis function working but may need tuning
"; } echo "
Analysis result: " . htmlspecialchars($analysisResult['reasoning']) . "
"; } else { echo "
❌ GPT connection failed: " . htmlspecialchars($response['error']) . "
"; } } catch (Exception $e) { echo "
❌ Error testing GPT: " . htmlspecialchars($e->getMessage()) . "
"; } } function resetAnalysisState() { global $db; try { // Stop any running analysis $db->query("UPDATE optimization_analysis_state SET is_running = 0, completed_at = NULL WHERE id > 0"); echo "
✅ Analysis state reset to stopped
"; // Reset processed count $db->query("UPDATE optimization_analysis_state SET processed_combinations = 0 WHERE id > 0"); echo "
✅ Progress counter reset
"; // Optionally reset all directives (uncomment if you want to start completely fresh) // $db->query("UPDATE panel_directives SET llm_checked = 0, is_impossible = 0, llm_reasoning = NULL, status = 'pending' WHERE id > 0"); // echo "
✅ All directives reset to unchecked state
"; echo "
ℹ️ Analysis state has been reset. You can now start a fresh analysis.
"; } catch (Exception $e) { echo "
❌ Error resetting analysis: " . htmlspecialchars($e->getMessage()) . "
"; } } function startAnalysis() { global $db; try { // Check if already running $stateResult = $db->query("SELECT is_running FROM optimization_analysis_state WHERE is_running = 1 LIMIT 1"); if ($stateResult && $stateResult->num_rows > 0) { echo "
⚠️ Analysis is already running
"; return; } // Get total combinations $totalResult = $db->query("SELECT COUNT(*) as count FROM panel_directives"); $totalCombinations = $totalResult->fetch_assoc()['count']; if ($totalCombinations == 0) { echo "
❌ No combinations found. Generate combinations first.
"; return; } // Mark as running $stmt = $db->prepare("UPDATE optimization_analysis_state SET is_running = 1, started_at = NOW(), total_combinations = ? WHERE id = (SELECT id FROM optimization_analysis_state ORDER BY id DESC LIMIT 1)"); $stmt->bind_param('i', $totalCombinations); $stmt->execute(); echo "
✅ Analysis marked as running
"; echo "
📊 Total combinations: " . number_format($totalCombinations) . "
"; // Start background process $command = "php " . __DIR__ . "/process_optimization_analysis.php > /dev/null 2>&1 &"; exec($command); echo "
✅ Background process started
"; echo "
ℹ️ The analysis will run in the background. Check progress in the OptimAIze page.
"; // Wait a moment and check if it started sleep(3); $logFile = __DIR__ . '/optimization_analysis.log'; if (file_exists($logFile)) { $logContent = file_get_contents($logFile); $recentEntries = substr($logContent, -1000); // Last 1000 characters echo "
📝 Recent log entries:
"; echo "
" . htmlspecialchars($recentEntries) . "
"; } } catch (Exception $e) { echo "
❌ Error starting analysis: " . htmlspecialchars($e->getMessage()) . "
"; } } function checkBackgroundProcess() { global $db; // Check if marked as running $stateResult = $db->query("SELECT * FROM optimization_analysis_state ORDER BY id DESC LIMIT 1"); $state = $stateResult ? $stateResult->fetch_assoc() : null; if ($state) { $statusClass = $state['is_running'] ? 'success' : 'info'; $statusText = $state['is_running'] ? 'RUNNING' : 'STOPPED'; echo "
Process Status: $statusText
"; if ($state['is_running']) { $progress = $state['total_combinations'] > 0 ? ($state['processed_combinations'] / $state['total_combinations']) * 100 : 0; echo "
📊 Progress: " . number_format($progress, 2) . "%
"; // Check recent activity $recentCount = $db->query("SELECT COUNT(*) as count FROM panel_directives WHERE llm_checked = 1 AND updated_at > DATE_SUB(NOW(), INTERVAL 2 MINUTE)")->fetch_assoc()['count']; if ($recentCount > 0) { echo "
✅ Active: $recentCount combinations processed in last 2 minutes
"; } else { echo "
⚠️ No recent activity - process may be stuck
"; } } } // Check log file $logFile = __DIR__ . '/optimization_analysis.log'; if (file_exists($logFile)) { $fileSize = filesize($logFile); $lastModified = date('Y-m-d H:i:s', filemtime($logFile)); echo "
📝 Log file: " . number_format($fileSize) . " bytes, last modified: $lastModified
"; // Show recent log entries $logContent = file_get_contents($logFile); $logLines = explode("\n", $logContent); $recentLines = array_slice($logLines, -10); // Last 10 lines echo "
Recent log entries:
"; echo "
";
        foreach ($recentLines as $line) {
            if (trim($line)) {
                echo htmlspecialchars($line) . "\n";
            }
        }
        echo "
"; } else { echo "
⚠️ Log file not found - background process may not be running
"; } } ?>