<?php

require __DIR__.'/vendor/autoload.php';

$app = require_once __DIR__.'/bootstrap/app.php';
$kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);
$kernel->bootstrap();

// Read the most recent Aliyun response from logs
$logFile = storage_path('logs/laravel.log');
$lines = file($logFile);

// Find the last "Aliyun Data Preview" entry
$lastDataPreview = null;
foreach (array_reverse($lines) as $line) {
    if (strpos($line, 'Aliyun Data Preview') !== false && strpos($line, '"data"') !== false) {
        $lastDataPreview = $line;
        break;
    }
}

if ($lastDataPreview) {
    // Extract JSON from log line
    preg_match('/"data":"(.+?)"}/', $lastDataPreview, $matches);
    
    if (isset($matches[1])) {
        $jsonStr = $matches[1];
        // Unescape
        $jsonStr = str_replace('\\"', '"', $jsonStr);
        $jsonStr = str_replace('\\\\', '\\', $jsonStr);
        
        $data = json_decode($jsonStr, true);
        
        if ($data && isset($data['page_list'][0]['answer_list'])) {
            echo "=== Answer List Structure ===\n\n";
            
            foreach ($data['page_list'][0]['answer_list'] as $i => $answer) {
                echo "Answer #{$i} (Question ID: " . json_encode($answer['ids'] ?? []) . "):\n";
                echo "  Text: " . ($answer['text'] ?? 'N/A') . "\n";
                echo "  All keys: " . implode(', ', array_keys($answer)) . "\n\n";
                
                if ($i >= 2) break; // Show first 3 answers
            }
            
            // Check if there's a pattern we can use
            echo "\n=== Analysis ===\n";
            echo "Total answers found: " . count($data['page_list'][0]['answer_list']) . "\n";
            
            // Check if text contains just the answer letter
            $firstAnswer = $data['page_list'][0]['answer_list'][0];
            $text = $firstAnswer['text'] ?? '';
            echo "First answer text length: " . mb_strlen($text) . " characters\n";
            echo "First answer text: " . $text . "\n";
            
        } else {
            echo "No answer_list found in response\n";
            echo "Available keys in page_list[0]: " . implode(', ', array_keys($data['page_list'][0] ?? [])) . "\n";
        }
    }
} else {
    echo "No Aliyun Data Preview found in logs\n";
}
