<?php

namespace NewsletterBridge\Utils;

/**
 * Formattazione log query feed (WP-CLI / admin dry-run).
 */
class FeedQueryLogger {

    /**
     * @param array<int, array{feed: string, step: string, args: array, posts_found?: int}> $entries
     */
    public static function formatForOutput(array $entries): string {
        if ($entries === []) {
            return "Nessuna query registrata.\n";
        }

        $lines = [];
        $current_feed = '';

        foreach ($entries as $entry) {
            if ($entry['feed'] !== $current_feed) {
                $current_feed = $entry['feed'];
                $lines[] = '';
                $lines[] = '=== Feed: ' . $current_feed . ' ===';
            }

            $lines[] = '--- ' . $entry['step'] . ' ---';
            $lines[] = self::summarizeArgs($entry['args']);
            if (isset($entry['posts_found'])) {
                $lines[] = 'Post trovati: ' . $entry['posts_found'];
            }
            $lines[] = 'Args (JSON): ' . wp_json_encode($entry['args'], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
        }

        return implode("\n", $lines);
    }

    /**
     * @param array<string, mixed> $args
     */
    public static function summarizeArgs(array $args): string {
        $parts = [];

        if (isset($args['post_type'])) {
            $pt = $args['post_type'];
            $parts[] = 'post_type: ' . (is_array($pt) ? implode(', ', $pt) : $pt);
        }
        if (isset($args['posts_per_page'])) {
            $parts[] = 'posts_per_page: ' . $args['posts_per_page'];
        }
        if (!empty($args['post__not_in'])) {
            $parts[] = 'post__not_in: ' . count((array) $args['post__not_in']) . ' id';
        }
        if (!empty($args['tax_query'])) {
            $parts[] = 'tax_query: ' . self::summarizeTaxQuery($args['tax_query']);
        }
        if (!empty($args['meta_query'])) {
            $parts[] = 'meta_query: ' . wp_json_encode($args['meta_query'], JSON_UNESCAPED_UNICODE);
        }
        if (!empty($args['date_query'])) {
            $parts[] = 'date_query: ' . wp_json_encode($args['date_query'], JSON_UNESCAPED_UNICODE);
        }

        return $parts !== [] ? implode(' | ', $parts) : '(nessun filtro aggiuntivo)';
    }

    /**
     * @param array<string, mixed> $tax_query
     */
    private static function summarizeTaxQuery(array $tax_query): string {
        $chunks = [];
        foreach ($tax_query as $key => $clause) {
            if ($key === 'relation') {
                continue;
            }
            if (!is_array($clause) || !isset($clause['taxonomy'])) {
                continue;
            }
            $terms = $clause['terms'] ?? [];
            $term_labels = [];
            if (is_array($terms)) {
                foreach ($terms as $term_id) {
                    $term = get_term((int) $term_id);
                    if ($term && !is_wp_error($term)) {
                        $term_labels[] = $term->taxonomy . ':' . $term->slug;
                    }
                }
            }
            $chunks[] = ($clause['taxonomy'] ?? '?') . ' ' . ($clause['operator'] ?? 'IN')
                . ' [' . implode(', ', $term_labels) . ']';
        }

        return $chunks !== [] ? implode('; ', $chunks) : wp_json_encode($tax_query);
    }
}
