












<?php
require_once __DIR__ . '/../vendor/autoload.php';

use OpenAI\Factory;

$logFile = __DIR__ . '/../curated_news_log.txt';
$curatedFile = __DIR__ . '/../curated_news.json';

// Your OpenAI API Key
$openAIKey = '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';

$newsDataFile = __DIR__ . '/curated_news.json';

if (file_exists($newsDataFile)) {
    $newsData = json_decode(file_get_contents($newsDataFile), true);
} else {
    $newsData = [];
}
$newsTitles= [];
if (!empty($newsData) && is_array($newsData)) {
    foreach ($newsData as $news) {
        // process news
        $newsTitles[] = [
            'title' => $item['title'],
            'source' => $item['url']
        ];
    }
} else {
    logMessage("No news data available to curate.");
}


// $newsTitles= [];
// foreach ($newsData['Data'] as $item) {
//     $newsTitles[] = [
//         'title' => $item['title'],
//         'source' => $item['url']
//     ];
// }

// Setup OpenAI Client
$client = (new Factory())->withApiKey($openAIKey)->make();

function logMessage($message) {
    global $logFile;
    file_put_contents($logFile, "[" . date('Y-m-d H:i:s') . "] $message\n", FILE_APPEND);
}

logMessage("===== Curated News Generation Started =====");

$curated = [];

foreach ($newsTitles as $title) {
    logMessage("Processing: $title");

    $prompt = "Provide a clear and concise summary and a key takeaway of the following crypto news title:\n\n\"$title\"\n\nFormat:\nSummary: <summary>\nTakeaway: <insight>";

    try {
        // Attempt with GPT-4 first
        try {
            $response = $client->chat()->create([
                'model' => 'gpt-4',
                'messages' => [
                    ['role' => 'system', 'content' => 'You are a crypto news analyst.'],
                    ['role' => 'user', 'content' => $prompt]
                ]
            ]);
        } catch (Exception $e) {
            logMessage("⚠️ GPT-4 not accessible: " . $e->getMessage() . " -- Falling back to GPT-3.5.");
            // Fallback to GPT-3.5
            $response = $client->chat()->create([
                'model' => 'gpt-3.5-turbo',
                'messages' => [
                    ['role' => 'system', 'content' => 'You are a crypto news analyst.'],
                    ['role' => 'user', 'content' => $prompt]
                ]
            ]);
        }

        $content = $response->choices[0]->message->content;

        // Parse summary and takeaway
        $summary = '';
        $takeaway = '';

        if (preg_match('/Summary:\s*(.*?)\s*Takeaway:/is', $content, $matches)) {
            $summary = trim($matches[1]);
        }
        if (preg_match('/Takeaway:\s*(.*)/is', $content, $matches)) {
            $takeaway = trim($matches[1]);
        }

        if (!$summary) {
            $summary = substr($content, 0, 100) . '...';
        }
        if (!$takeaway) {
            $takeaway = 'No key takeaway provided.';
        }

        $curated[] = [
            'title' => $title,
            'summary' => $summary,
            'takeaway' => $takeaway,
            'timestamp' => date('Y-m-d H:i:s')
        ];

        logMessage("✅ Successfully processed: $title");

    } catch (Exception $e) {
        logMessage("❌ Error processing '$title': " . $e->getMessage());
    }
}

if (!empty($curated)) {
    if (file_put_contents($curatedFile, json_encode($curated, JSON_PRETTY_PRINT))) {
        logMessage("✅ Curated news saved to curated_news.json.");
    } else {
        logMessage("❌ Failed to write to curated_news.json. Check permissions.");
    }
} else {
    logMessage("❌ No curated news generated.");
}

logMessage("===== Curated News Generation Completed =====");

echo "Curated news generation completed. Check log for details.";
