<?php
/**
 * Strategy health counts — GET /api/strategy/health
 * Was routed in index.php but had no backing file (a real, pre-existing
 * bug, found during the 2026-08-11 Strategy redesign inspection) — the
 * page's own refreshHealthStats() call (fired after every archive) has
 * always silently failed. Mirrors the exact query public/strategy.php
 * already runs server-side on page load, so the two can never disagree.
 */
header('Content-Type: application/json');

try {
    $userId = $auth->requireAuth();

    $healthStats = $db->raw("
        SELECT
            COUNT(*) AS total_active,
            SUM(CASE WHEN trade_count < 10 OR trade_count IS NULL THEN 1 ELSE 0 END) AS low_activity_count,
            SUM(CASE WHEN days_since_last > 30 OR days_since_last IS NULL THEN 1 ELSE 0 END) AS stale_count
        FROM (
            SELECT
                s.id,
                COUNT(t.id) AS trade_count,
                DATEDIFF(NOW(), MAX(t.closed_at)) AS days_since_last
            FROM strategies s
            LEFT JOIN strategy_versions sv ON sv.strategy_id = s.id
            LEFT JOIN trades t ON t.strategy_version_id = sv.id AND t.status = 'closed' AND t.deleted_at IS NULL
            WHERE s.user_id = :uid AND s.is_active = 1 AND s.deleted_at IS NULL
            GROUP BY s.id
        ) sub
    ", [':uid' => $userId]);

    echo json_encode([
        'totalActive' => (int)($healthStats[0]['total_active'] ?? 0),
        'lowActivityCount' => (int)($healthStats[0]['low_activity_count'] ?? 0),
        'staleCount' => (int)($healthStats[0]['stale_count'] ?? 0),
    ]);
} catch (\Throwable $e) {
    error_log('Strategy health error: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode(['error' => 'Server error']);
}
