<?php
/**
 * سودانا — Metrics Updater v21
 * Single source of truth — يحسب الأرقام الحقيقية من الكود وقاعدة البيانات
 * Usage: php engine/MetricsUpdater.php
 * Cron:  0 * * * * php /path/to/engine/MetricsUpdater.php
 */

// Allow CLI and HTTP (admin only)
$isCli = PHP_SAPI === 'cli';
if (!$isCli) {
    require_once dirname(__DIR__) . '/config.php';
    session_start();
    if (empty($_SESSION['admin']) && ($_GET['key'] ?? '') !== ADMIN_PASSWORD) {
        http_response_code(403);
        die(json_encode(['error' => 'unauthorized']));
    }
}

$metricsFile = dirname(__DIR__) . '/system/system_metrics.json';
$metrics = [];

// ── 1. Count IE rules from InferenceEngine.php ────────────────
$ieFile = dirname(__DIR__) . '/engine/InferenceEngine.php';
$ieContent = file_get_contents($ieFile) ?: '';
$metrics['ie_rules_count'] = substr_count($ieContent, "'id'=>'");

// ── 2. DB Counts ──────────────────────────────────────────────
$dbCounts = [
    'providers_count'  => 0,
    'experts_count'    => 0,
    'services_count'   => 0,
    'pharmacies_count' => 0,
    'lessons_count'    => 0,
    'users_count'      => 0,
    'bde_docs_count'   => 0,
];

try {
    if (!$isCli) {
        $db = db();
    } else {
        // Load config for CLI
        require_once dirname(__DIR__) . '/config.php';
        $db = db();
    }

    $queries = [
        'providers_count'  => "SELECT COUNT(*) FROM users WHERE provider_verified=1",
        'experts_count'    => "SELECT COUNT(*) FROM users WHERE provider_verified=1 AND user_type IN ('doctor','academic','service_provider')",
        'services_count'   => "SELECT COUNT(*) FROM provider_services WHERE is_active=1",
        'pharmacies_count' => "SELECT COUNT(*) FROM pharmacies WHERE status='active'",
        'lessons_count'    => "SELECT COUNT(*) FROM lessons WHERE status='published'",
        'users_count'      => "SELECT COUNT(*) FROM users",
        'bde_docs_count'   => "SELECT COUNT(*) FROM bde_documents WHERE status='ready'",
    ];

    foreach ($queries as $key => $sql) {
        try {
            $dbCounts[$key] = (int) $db->query($sql)->fetchColumn();
        } catch (Throwable $e) {
            $dbCounts[$key] = 0; // Table may not exist yet
        }
    }
} catch (Throwable $e) {
    // DB not available — keep zeros
    if ($isCli) echo "WARNING: DB not available: " . $e->getMessage() . "\n";
}

// ── 3. Count API files ────────────────────────────────────────
$apiDir   = dirname(__DIR__) . '/api';
$apiFiles = [];
if (is_dir($apiDir)) {
    $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($apiDir));
    foreach ($it as $f) {
        if ($f->isFile() && $f->getExtension() === 'php') {
            $apiFiles[] = str_replace(dirname(__DIR__) . '/', '', $f->getPathname());
        }
    }
}

// ── 4. Count DB tables ────────────────────────────────────────
$migrate1 = dirname(__DIR__) . '/migrate.sql';
$migrate2 = dirname(__DIR__) . '/migrate_v21.sql';
$tableCount = 0;
foreach ([$migrate1, $migrate2] as $f) {
    if (file_exists($f)) {
        $tableCount += substr_count(file_get_contents($f), 'CREATE TABLE');
    }
}

// ── 5. Build metrics object ───────────────────────────────────
$metrics = array_merge($metrics, $dbCounts, [
    'api_files_count' => count($apiFiles),
    'db_tables_count' => $tableCount,
    'bde_templates_count' => 5, // from seed data
    'version'         => 'v21',
    'last_updated'    => gmdate('Y-m-d\TH:i:s\Z'),
    'generated_by'    => $isCli ? 'cli' : 'http',
]);

// ── 6. Write to system_metrics.json ──────────────────────────
$dir = dirname($metricsFile);
if (!is_dir($dir)) mkdir($dir, 0755, true);
file_put_contents($metricsFile, json_encode($metrics, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));

// ── Output ────────────────────────────────────────────────────
if ($isCli) {
    echo "✅ Metrics updated:\n";
    echo "   IE Rules:       {$metrics['ie_rules_count']}\n";
    echo "   Providers:      {$metrics['providers_count']}\n";
    echo "   Experts:        {$metrics['experts_count']}\n";
    echo "   Services:       {$metrics['services_count']}\n";
    echo "   Pharmacies:     {$metrics['pharmacies_count']}\n";
    echo "   Lessons:        {$metrics['lessons_count']}\n";
    echo "   Users:          {$metrics['users_count']}\n";
    echo "   API Files:      {$metrics['api_files_count']}\n";
    echo "   DB Tables:      {$metrics['db_tables_count']}\n";
    echo "   Updated:        {$metrics['last_updated']}\n";
} else {
    header('Content-Type: application/json');
    echo json_encode(['success' => true, 'metrics' => $metrics], JSON_UNESCAPED_UNICODE);
}
