<?php
/* fetch_news.php — с детектором нестандартной активности */

function curlGet($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Avatiah-OSINT/1.0 (research)');
    curl_setopt($ch, CURLOPT_ENCODING, '');
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}

function getNewsForQuery($query, $language = 'en') {
    $encoded = urlencode($query);
    $url = "https://news.google.com/rss/search?q={$encoded}&hl={$language}&gl=US&ceid=US:{$language}";
    $xml = curlGet($url);
    if (!$xml) return [];
    
    $rss = simplexml_load_string($xml);
    if (!$rss) return [];
    
    $items = [];
    foreach ($rss->channel->item as $item) {
        if (count($items) >= 3) break; // Только свежие 3
        $pubDate = strtotime((string)$item->pubDate);
        // Только за последние 72 часа
        if ($pubDate > time() - 72*3600) {
            $items[] = [
                'title' => (string)$item->title,
                'link' => (string)$item->link,
                'pubDate' => (string)$item->pubDate,
                'source' => (string)$item->source
            ];
        }
    }
    return $items;
}

// Ключевые запросы для OSINT-детекции
$queries = [
    'Israel satellite increased activity Iran' => 'en',
    'Ofek-19 emergency passes' => 'en',
    'Israeli spy satellite anomaly' => 'en',
    'cyberattack Israeli ground station' => 'en',
    'Iran nuclear site confirmed satellite' => 'en',
    'Dror-1 outage Israel' => 'en',
    'IAI satellite urgent imagery' => 'en',
    'Israel Iran escalation satellite' => 'en'
];

$all_news = [];
$all_news_text = '';

foreach ($queries as $q => $lang) {
    $news = getNewsForQuery($q, $lang);
    if (!empty($news)) {
        $all_news[$q] = $news;
        foreach ($news as $item) {
            $all_news_text .= ' ' . strtolower($item['title']);
        }
    }
    usleep(200000);
}

// === ДЕТЕКТОР НЕСТАНДАРТНОЙ АКТИВНОСТИ ===
$alert_signals = [
    'increased satellite activity' => 0.2,
    'additional passes' => 0.2,
    'emergency passes' => 0.3,
    'satellite anomaly' => 0.3,
    'cyberattack' => 0.4,
    'confirmed nuclear site' => 0.2,
    'urgent imagery' => 0.2,
    'escalation' => 0.2,
    'outage' => 0.3
];

$detected_signals = [];
$aal_adjustment = 0;

foreach ($alert_signals as $phrase => $weight) {
    if (strpos($all_news_text, $phrase) !== false) {
        $detected_signals[] = [
            'phrase' => $phrase,
            'weight' => $weight,
            'evidence' => array_filter($all_news, function($items) use ($phrase) {
                foreach ($items as $item) {
                    if (stripos($item['title'], $phrase) !== false) return true;
                }
                return false;
            })
        ];
        $aal_adjustment += $weight;
    }
}

// Сохраняем данные о сигналах
$signals_file = __DIR__ . '/anomaly_signals.json';
file_put_contents($signals_file, json_encode([
    'last_update' => date('d.m.Y H:i') . ' UTC',
    'detected_signals' => $detected_signals,
    'aal_adjustment' => round($aal_adjustment, 1),
    'raw_news_text' => substr($all_news_text, 0, 500) . '...'
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));

// Сохраняем новости
$output_file = __DIR__ . '/israel_satellite_news.json';
file_put_contents($output_file, json_encode([
    'source' => 'Google News RSS (OSINT)',
    'last_update' => date('d.m.Y H:i') . ' UTC',
    'queries' => array_keys($queries),
    'news' => $all_news,
    'anomaly_detected' => !empty($detected_signals),
    'aal_adjustment' => round($aal_adjustment, 1)
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));

echo json_encode([
    'status' => 'success',
    'file' => 'israel_satellite_news.json',
    'anomaly_detected' => !empty($detected_signals),
    'aal_adjustment' => round($aal_adjustment, 1),
    'signals_count' => count($detected_signals),
    'sample_signal' => !empty($detected_signals) ? $detected_signals[0]['phrase'] : null
], JSON_UNESCAPED_UNICODE);
?>