<?php
/**
 * RSS Feed Runner - API Backend
 * Returns JSON output for the monitoring interface
 */

header('Content-Type: application/json');
set_time_limit(0);
ini_set('max_execution_time', 600);

// Capture output
ob_start();

// Run x_feeds.php
include 'x_feeds.php';

$output = ob_get_clean();

// Parse output to extract stats and logs
$logs = [];
$stats = [
    'sources' => 0,
    'processed' => 0,
    'skipped' => 0,
    'errors' => 0
];

// Extract log lines
preg_match_all('/\[([^\]]+)\]\[([^\]]+)\]\s*(.+)/', $output, $matches, PREG_SET_ORDER);

foreach ($matches as $match) {
    $logs[] = [
        'time' => $match[1],
        'type' => $match[2],
        'message' => strip_tags($match[3])
    ];
}

// Extract stats from summary
if (preg_match('/Sources processed:\s*(\d+)/', $output, $m)) {
    $stats['sources'] = (int) $m[1];
}
if (preg_match('/Posts inserted:\s*(\d+)/', $output, $m)) {
    $stats['processed'] = (int) $m[1];
}
if (preg_match('/Posts skipped:\s*(\d+)/', $output, $m)) {
    $stats['skipped'] = (int) $m[1];
}
if (preg_match('/Errors:\s*(\d+)/', $output, $m)) {
    $stats['errors'] = (int) $m[1];
}

echo json_encode([
    'stats' => $stats,
    'logs' => $logs,
    'timestamp' => date('Y-m-d H:i:s')
], JSON_UNESCAPED_UNICODE);
