package de.assecutor.votianlt.ai.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import de.assecutor.votianlt.model.Job;
import de.assecutor.votianlt.model.JobStatus;
import de.assecutor.votianlt.service.JobStatisticsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.Month;
import java.time.Year;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Service for AI-assisted statistics analysis with chart visualization. Uses LM
 * Studio via direct REST client (like aimailassistant) instead of Spring AI.
 */
@Service
@Slf4j
public class AiStatisticsService {

    private final LlmRestClient llmClient;
    private final JobStatisticsService statisticsService;
    private final ObjectMapper objectMapper;

    public AiStatisticsService(LlmRestClient llmClient, JobStatisticsService statisticsService) {
        this.llmClient = llmClient;
        this.statisticsService = statisticsService;
        this.objectMapper = new ObjectMapper();
        log.info("AiStatisticsService initialized with direct REST client");
    }

    /**
     * Response record containing text and optional chart data.
     */
    public record StatisticsResponse(String textResponse, String chartType, String chartData) {
    }

    /**
     * Analyze a statistics query and return a response with optional visualization.
     */
    public StatisticsResponse analyzeStatisticsQuery(String userQuery) {
        log.info("Processing statistics query: {}", userQuery);

        // Determine query type and prepare chart data (includes customer filter
        // detection)
        QueryAnalysis analysis = analyzeQueryType(userQuery);
        log.debug("Query analysis - Type: {}, Chart: {}, Customer: {}, Status: {}", analysis.queryType,
                analysis.chartType, analysis.customerFilter != null ? analysis.customerFilter : "none",
                analysis.statusFilter != null ? analysis.statusFilter : "none");

        // Gather context (statistics or job list depending on query type)
        String statisticsContext = buildStatisticsContext(analysis);

        // Build prompt for LLM
        String prompt = buildPrompt(userQuery, statisticsContext, analysis);

        // System prompt - different for list vs statistics queries
        String systemPrompt = analysis.queryType.equals("list") ? buildListSystemPrompt()
                : buildStatisticsSystemPrompt();

        // Call LLM via direct REST client (like aimailassistant)
        String llmResponse = llmClient.chat(systemPrompt, prompt);

        if (llmResponse != null && !llmResponse.isBlank()) {
            log.info("LLM response received, length: {} chars", llmResponse.length());
            return new StatisticsResponse(llmResponse, analysis.chartType, analysis.chartData);
        } else {
            log.warn("LLM returned null or blank response, using fallback");
            return new StatisticsResponse(buildFallbackResponse(analysis), analysis.chartType, analysis.chartData);
        }
    }

    private record QueryAnalysis(String queryType, String chartType, String chartData, String customerFilter, // null =
                                                                                                              // no
                                                                                                              // filter,
                                                                                                              // show
                                                                                                              // all
                                                                                                              // data
            JobStatus statusFilter // null = no status filter
    ) {
    }

    private String buildStatisticsSystemPrompt() {
        return """
                Du bist ein Statistik-Assistent für ein Logistikunternehmen.

                WICHTIG - ANTWORTSTIL:
                - Beantworte NUR die gestellte Frage - keine zusätzlichen Informationen!
                - Keine allgemeinen Tipps, Empfehlungen oder weiterführende Hinweise
                - Keine Vergleiche mit anderen Daten, außer explizit gefragt
                - Kurz und präzise: maximal 2-3 Sätze
                - Nenne die relevanten Zahlen direkt

                DIAGRAMM-HINWEIS:
                - Ein Diagramm wird AUTOMATISCH angezeigt - nicht erwähnen oder beschreiben
                - Sage NIEMALS "Ich kann kein Diagramm zeichnen" oder ähnliches

                FORMATIERUNG:
                - Keine Tabellen
                - Keine langen Aufzählungen
                - Fließtext bevorzugen

                Antworte auf Deutsch.
                """;
    }

    private String buildListSystemPrompt() {
        return """
                Du bist ein Assistent für ein Logistikunternehmen.

                WICHTIG - ANTWORTSTIL:
                - Der Benutzer fragt nach einer Liste von Jobs/Aufträgen
                - Die Job-Liste wird bereits als Daten angezeigt
                - Fasse nur kurz zusammen, was gefunden wurde (z.B. "Es wurden X Jobs gefunden")
                - Keine detaillierte Auflistung der Jobs nötig - die Daten sind bereits sichtbar
                - Maximal 1-2 Sätze

                KEIN DIAGRAMM:
                - Es wird KEIN Diagramm angezeigt bei Listen-Anfragen
                - Erwähne keine Diagramme

                Antworte auf Deutsch.
                """;
    }

    /**
     * Detect user-specified chart type from the query. Returns null if no specific
     * chart type was requested.
     */
    private String detectUserChartTypePreference(String query) {
        String lowerQuery = query.toLowerCase();

        // Balkendiagramm / Bar Chart
        if (lowerQuery.contains("balken") || lowerQuery.contains("bar chart") || lowerQuery.contains("säulen")
                || lowerQuery.contains("balkendiagramm")) {
            return "bar";
        }

        // Tortendiagramm / Pie Chart
        if (lowerQuery.contains("torten") || lowerQuery.contains("pie") || lowerQuery.contains("kreis")
                || lowerQuery.contains("tortendiagramm") || lowerQuery.contains("kreisdiagramm")) {
            return "pie";
        }

        // Donut / Ring Chart
        if (lowerQuery.contains("donut") || lowerQuery.contains("ring") || lowerQuery.contains("doughnut")) {
            return "doughnut";
        }

        // Liniendiagramm / Line Chart
        if (lowerQuery.contains("linie") || lowerQuery.contains("line") || lowerQuery.contains("liniendiagramm")
                || lowerQuery.contains("kurve") || lowerQuery.contains("graph")) {
            return "line";
        }

        // Flächendiagramm / Area Chart
        if (lowerQuery.contains("fläche") || lowerQuery.contains("area") || lowerQuery.contains("flächendiagramm")) {
            return "line"; // Line with fill=true
        }

        // Radar Chart
        if (lowerQuery.contains("radar") || lowerQuery.contains("netz") || lowerQuery.contains("spinne")) {
            return "radar";
        }

        // Polararea Chart
        if (lowerQuery.contains("polar")) {
            return "polarArea";
        }

        return null; // No specific preference
    }

    private QueryAnalysis analyzeQueryType(String query) {
        String lowerQuery = query.toLowerCase();

        // First, check if this is a LIST query (no chart needed)
        boolean isListQuery = isListQuery(lowerQuery);
        log.debug("Is list query: {}", isListQuery);

        // Check if user specified a chart type (only relevant for non-list queries)
        String userChartType = isListQuery ? null : detectUserChartTypePreference(query);
        log.debug("User chart type preference: {}", userChartType != null ? userChartType : "none");

        // Check if user specified a customer filter
        String customerFilter = detectCustomerFilter(query);
        log.debug("Customer filter: {}", customerFilter != null ? customerFilter : "none (showing all data)");

        // Check if user specified a status filter
        JobStatus statusFilter = detectStatusFilter(lowerQuery);
        log.debug("Status filter: {}", statusFilter != null ? statusFilter : "none");

        // For list queries, return no chart
        if (isListQuery) {
            return new QueryAnalysis("list", null, null, customerFilter, statusFilter);
        }

        // Determine query type and default chart type
        String queryType;
        String defaultChartType;
        String chartData;

        // Status-bezogene Anfragen (Statistik, nicht Liste)
        if ((lowerQuery.contains("status") && (lowerQuery.contains("statistik") || lowerQuery.contains("verteilung")
                || lowerQuery.contains("übersicht") || lowerQuery.contains("wie viele")))
                || lowerQuery.contains("zählen") || lowerQuery.contains("anzahl")) {
            queryType = "status";
            defaultChartType = "doughnut";
            chartData = buildStatusChartData(customerFilter);
        }
        // Umsatz-bezogene Anfragen
        else if (lowerQuery.contains("umsatz") || lowerQuery.contains("revenue") || lowerQuery.contains("einnahmen")) {
            queryType = "revenue";
            defaultChartType = "bar";
            chartData = customerFilter != null ? buildCustomerRevenueChartData(customerFilter)
                    : buildRevenueChartData();
        }
        // Trend-bezogene Anfragen
        else if (lowerQuery.contains("trend") || lowerQuery.contains("monat") || lowerQuery.contains("entwicklung")
                || lowerQuery.contains("jahr") || lowerQuery.contains("verlauf")) {
            queryType = "trend";
            defaultChartType = "line";
            chartData = buildTrendChartData(customerFilter);
        }
        // Task-bezogene Anfragen
        else if (lowerQuery.contains("task") || lowerQuery.contains("aufgabe") || lowerQuery.contains("erledigt")) {
            queryType = "tasks";
            defaultChartType = "doughnut";
            chartData = buildTaskChartData();
        }
        // Allgemeine Übersicht
        else {
            queryType = "overview";
            defaultChartType = "bar";
            chartData = buildOverviewChartData(customerFilter);
        }

        // Use user's chart type preference if specified, otherwise use default
        String chartType = userChartType != null ? userChartType : defaultChartType;

        return new QueryAnalysis(queryType, chartType, chartData, customerFilter, null);
    }

    /**
     * Detect status filter from the query.
     */
    private JobStatus detectStatusFilter(String lowerQuery) {
        if (lowerQuery.contains("angelegt") || lowerQuery.contains("erstellt") || lowerQuery.contains("created")) {
            return JobStatus.CREATED;
        }
        if (lowerQuery.contains("in bearbeitung") || lowerQuery.contains("in progress")) {
            return JobStatus.IN_PROGRESS;
        }
        if (lowerQuery.contains("abholung geplant") || lowerQuery.contains("pickup scheduled")) {
            return JobStatus.PICKUP_SCHEDULED;
        }
        if (lowerQuery.contains("abgeholt") || lowerQuery.contains("picked up")) {
            return JobStatus.PICKED_UP;
        }
        if (lowerQuery.contains("in transport") || lowerQuery.contains("in transit")
                || lowerQuery.contains("unterwegs")) {
            return JobStatus.IN_TRANSIT;
        }
        if (lowerQuery.contains("zugestellt") || lowerQuery.contains("delivered") || lowerQuery.contains("geliefert")) {
            return JobStatus.DELIVERED;
        }
        if (lowerQuery.contains("abgeschlossen") || lowerQuery.contains("completed") || lowerQuery.contains("fertig")) {
            return JobStatus.COMPLETED;
        }
        if (lowerQuery.contains("storniert") || lowerQuery.contains("cancelled")
                || lowerQuery.contains("abgebrochen")) {
            return JobStatus.CANCELLED;
        }
        return null;
    }

    /**
     * Detect if the query is asking for a list of jobs (not statistics).
     */
    private boolean isListQuery(String lowerQuery) {
        // Keywords that indicate a list/detail query (not statistics)
        boolean hasListKeywords = lowerQuery.contains("zeige alle") || lowerQuery.contains("liste")
                || lowerQuery.contains("welche jobs") || lowerQuery.contains("alle jobs")
                || lowerQuery.contains("alle aufträge") || lowerQuery.contains("zeige die jobs")
                || lowerQuery.contains("zeige die aufträge") || lowerQuery.contains("zeig mir die")
                || lowerQuery.contains("gib mir die");

        // Keywords that indicate statistics (override list detection)
        boolean hasStatsKeywords = lowerQuery.contains("statistik") || lowerQuery.contains("diagramm")
                || lowerQuery.contains("chart") || lowerQuery.contains("verteilung") || lowerQuery.contains("wie viele")
                || lowerQuery.contains("anzahl") || lowerQuery.contains("zähle") || lowerQuery.contains("umsatz")
                || lowerQuery.contains("trend") || lowerQuery.contains("torte") || lowerQuery.contains("balken");

        return hasListKeywords && !hasStatsKeywords;
    }

    /**
     * Detect customer filter from the query. Returns the matching customer name or
     * null if no filter detected.
     */
    private String detectCustomerFilter(String query) {
        String lowerQuery = query.toLowerCase();

        // Keywords that indicate a customer filter
        String[] filterIndicators = { "für ", "von ", "bei ", "kunde ", "firma ", "unternehmen ", "für die firma ",
                "für den kunden ", "von der firma ", "vom kunden ", "nur ", "ausschließlich ", "speziell " };

        // Check if any indicator is present
        boolean hasIndicator = false;
        String foundIndicator = null;
        for (String indicator : filterIndicators) {
            int idx = lowerQuery.indexOf(indicator);
            if (idx >= 0) {
                hasIndicator = true;
                foundIndicator = indicator;
                break;
            }
        }

        if (!hasIndicator) {
            log.debug("detectCustomerFilter - No filter indicator found in: '{}'", query);
            return null;
        }

        log.debug("detectCustomerFilter - Found indicator '{}' in query: '{}'", foundIndicator, query);

        // Try to find a matching customer in the query
        String matchedCustomer = statisticsService.findMatchingCustomer(query);
        log.debug("detectCustomerFilter - Matched customer: '{}'", matchedCustomer);
        return matchedCustomer;
    }

    private String buildStatusChartData(String customerFilter) {
        Map<JobStatus, Long> statusCounts = customerFilter != null
                ? statisticsService.getJobCountsByStatusForCustomer(customerFilter)
                : statisticsService.getJobCountsByStatus();

        List<String> labels = new ArrayList<>();
        List<Long> data = new ArrayList<>();
        // Moderne Farbpalette mit satteren Farben
        List<String> colors = List.of("#06b6d4", // CREATED - cyan
                "#f59e0b", // IN_PROGRESS - amber
                "#3b82f6", // PICKUP_SCHEDULED - blau
                "#8b5cf6", // PICKED_UP - violett
                "#f97316", // IN_TRANSIT - orange
                "#22c55e", // DELIVERED - grün
                "#6366f1", // COMPLETED - indigo
                "#ef4444" // CANCELLED - rot
        );

        for (JobStatus status : JobStatus.values()) {
            Long count = statusCounts.getOrDefault(status, 0L);
            if (count > 0) {
                labels.add(status.getDisplayName());
                data.add(count);
            }
        }

        String label = customerFilter != null ? "Aufträge (" + customerFilter + ")" : "Aufträge";
        return buildChartJson(labels, data, colors.subList(0, Math.min(labels.size(), colors.size())), label);
    }

    private String buildRevenueChartData() {
        var topCustomers = statisticsService.getTopCustomersByRevenue(10);

        List<String> labels = new ArrayList<>();
        List<Double> data = new ArrayList<>();

        for (var entry : topCustomers) {
            labels.add(entry.getKey() != null ? entry.getKey() : "Unbekannt");
            data.add(entry.getValue().doubleValue());
        }

        // Gradient-ähnliche Farbpalette für Balken
        List<String> colors = List.of("#6366f1", "#8b5cf6", "#a855f7", "#c084fc", "#d8b4fe", "#e9d5ff", "#f3e8ff",
                "#faf5ff", "#ede9fe", "#ddd6fe");
        return buildChartJsonDouble(labels, data, colors.subList(0, Math.min(labels.size(), colors.size())),
                "Umsatz (EUR)");
    }

    private String buildCustomerRevenueChartData(String customer) {
        var statusCounts = statisticsService.getJobCountsByStatusForCustomer(customer);
        var totalRevenue = statisticsService.getTotalRevenueForCustomer(customer);
        long totalJobs = statisticsService.getTotalJobCountForCustomer(customer);
        long completed = statusCounts.getOrDefault(JobStatus.COMPLETED, 0L);
        long inProgress = statusCounts.getOrDefault(JobStatus.IN_PROGRESS, 0L);

        List<String> labels = List.of("Aufträge gesamt", "Abgeschlossen", "In Bearbeitung", "Umsatz (€/100)");
        List<Double> data = List.of((double) totalJobs, (double) completed, (double) inProgress,
                totalRevenue.doubleValue() / 100 // Scale down for better visualization
        );
        List<String> colors = List.of("#3b82f6", "#22c55e", "#f59e0b", "#6366f1");

        return buildChartJsonDouble(labels, data, colors, customer);
    }

    private String buildTrendChartData(String customerFilter) {
        int currentYear = Year.now().getValue();
        Map<Month, Long> monthlyData = customerFilter != null
                ? statisticsService.getMonthlyJobCountsForCustomer(currentYear, customerFilter)
                : statisticsService.getMonthlyJobCounts(currentYear);

        List<String> labels = List.of("Jan", "Feb", "Mär", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov",
                "Dez");
        List<Long> data = new ArrayList<>();

        for (Month month : Month.values()) {
            data.add(monthlyData.getOrDefault(month, 0L));
        }

        String datasetLabel = customerFilter != null ? String.format("%s - %d", customerFilter, currentYear)
                : String.format("Aufträge %d", currentYear);

        return String.format("""
                {
                    "labels": %s,
                    "datasets": [{
                        "label": "%s",
                        "data": %s,
                        "borderColor": "#6366f1",
                        "backgroundColor": "rgba(99, 102, 241, 0.15)",
                        "pointBackgroundColor": "#6366f1",
                        "pointBorderColor": "#fff",
                        "pointBorderWidth": 2,
                        "pointRadius": 5,
                        "pointHoverRadius": 7,
                        "tension": 0.4,
                        "fill": true
                    }]
                }
                """, toJsonArray(labels), datasetLabel, data);
    }

    private String buildTaskChartData() {
        Map<String, Long> taskStats = statisticsService.getTaskCompletionStats();

        List<String> labels = List.of("Erledigt", "Ausstehend");
        List<Long> data = List.of(taskStats.getOrDefault("completed", 0L), taskStats.getOrDefault("pending", 0L));
        List<String> colors = List.of("#22c55e", "#f59e0b");

        return buildChartJson(labels, data, colors, "Aufgaben");
    }

    private String buildOverviewChartData(String customerFilter) {
        Map<JobStatus, Long> statusCounts = customerFilter != null
                ? statisticsService.getJobCountsByStatusForCustomer(customerFilter)
                : statisticsService.getJobCountsByStatus();

        long total = customerFilter != null ? statisticsService.getTotalJobCountForCustomer(customerFilter)
                : statisticsService.getTotalJobCount();
        long completed = statusCounts.getOrDefault(JobStatus.COMPLETED, 0L);
        long inProgress = statusCounts.getOrDefault(JobStatus.IN_PROGRESS, 0L);
        long open = total - completed - statusCounts.getOrDefault(JobStatus.CANCELLED, 0L);

        List<String> labels = List.of("Gesamt", "Abgeschlossen", "In Bearbeitung", "Offen");
        List<Long> data = List.of(total, completed, inProgress, open);
        List<String> colors = List.of("#3b82f6", "#22c55e", "#f59e0b", "#06b6d4");

        String label = customerFilter != null ? customerFilter : "Aufträge";
        return buildChartJson(labels, data, colors, label);
    }

    private String buildChartJson(List<String> labels, List<Long> data, List<String> colors, String label) {
        return String.format("""
                {
                    "labels": %s,
                    "datasets": [{
                        "label": "%s",
                        "data": %s,
                        "backgroundColor": %s,
                        "borderWidth": 1
                    }]
                }
                """, toJsonArray(labels), label, data, toJsonArray(colors));
    }

    private String buildChartJsonDouble(List<String> labels, List<Double> data, List<String> colors, String label) {
        return String.format("""
                {
                    "labels": %s,
                    "datasets": [{
                        "label": "%s",
                        "data": %s,
                        "backgroundColor": %s,
                        "borderWidth": 1
                    }]
                }
                """, toJsonArray(labels), label, data, toJsonArray(colors));
    }

    private String toJsonArray(List<String> list) {
        try {
            return objectMapper.writeValueAsString(list);
        } catch (JsonProcessingException e) {
            return "[]";
        }
    }

    private String buildStatisticsContext(QueryAnalysis analysis) {
        StringBuilder context = new StringBuilder();
        String customerFilter = analysis.customerFilter;
        JobStatus statusFilter = analysis.statusFilter;

        // For LIST queries, show actual job data
        if ("list".equals(analysis.queryType)) {
            return buildListContext(customerFilter, statusFilter);
        }

        // For statistics queries
        if (customerFilter != null) {
            // Filtered statistics for a specific customer
            context.append(String.format("**Statistiken für Kunde: %s**\n\n", customerFilter));

            var statusCounts = statisticsService.getJobCountsByStatusForCustomer(customerFilter);
            context.append("**Aufträge nach Status:**\n");
            statusCounts.forEach((status, count) -> {
                if (count > 0) {
                    context.append(String.format("- %s: %d Aufträge\n", status.getDisplayName(), count));
                }
            });

            context.append(String.format("\n**Übersicht für %s:**\n", customerFilter));
            context.append(String.format("- Gesamtanzahl Aufträge: %d\n",
                    statisticsService.getTotalJobCountForCustomer(customerFilter)));
            context.append(String.format("- Abschlussrate: %.1f%%\n",
                    statisticsService.getCompletionRateForCustomer(customerFilter)));
            context.append(String.format("- Umsatz: %.2f EUR\n",
                    statisticsService.getTotalRevenueForCustomer(customerFilter)));
        } else {
            // General statistics (all data)
            var statusCounts = statisticsService.getJobCountsByStatus();
            context.append("**Aktuelle Auftragsstatistiken:**\n");
            statusCounts.forEach((status, count) -> context
                    .append(String.format("- %s: %d Aufträge\n", status.getDisplayName(), count)));

            context.append(String.format("\n**Gesamtübersicht:**\n"));
            context.append(String.format("- Gesamtanzahl Aufträge: %d\n", statisticsService.getTotalJobCount()));
            context.append(String.format("- Abschlussrate: %.1f%%\n", statisticsService.getCompletionRate()));
            context.append(String.format("- Gesamtumsatz: %.2f EUR\n", statisticsService.getTotalRevenue()));

            // Task statistics
            var taskStats = statisticsService.getTaskCompletionStats();
            context.append(String.format("\n**Aufgaben:**\n"));
            context.append(String.format("- Gesamt: %d\n", taskStats.get("total")));
            context.append(String.format("- Erledigt: %d\n", taskStats.get("completed")));
            context.append(String.format("- Ausstehend: %d\n", taskStats.get("pending")));

            // Top customers
            var topCustomers = statisticsService.getTopCustomersByRevenue(5);
            if (!topCustomers.isEmpty()) {
                context.append("\n**Top 5 Kunden nach Umsatz:**\n");
                for (var entry : topCustomers) {
                    context.append(String.format("- %s: %.2f EUR\n",
                            entry.getKey() != null ? entry.getKey() : "Unbekannt", entry.getValue()));
                }
            }
        }

        return context.toString();
    }

    private String buildListContext(String customerFilter, JobStatus statusFilter) {
        StringBuilder context = new StringBuilder();

        List<Job> jobs;
        if (customerFilter != null && statusFilter != null) {
            jobs = statisticsService.getJobsByCustomerAndStatus(customerFilter, statusFilter);
            context.append(
                    String.format("**Jobs für %s mit Status %s:**\n\n", customerFilter, statusFilter.getDisplayName()));
        } else if (customerFilter != null) {
            jobs = statisticsService.getJobsByCustomer(customerFilter);
            context.append(String.format("**Jobs für %s:**\n\n", customerFilter));
        } else if (statusFilter != null) {
            jobs = statisticsService.getJobsByStatus(statusFilter);
            context.append(String.format("**Jobs mit Status %s:**\n\n", statusFilter.getDisplayName()));
        } else {
            jobs = statisticsService.getLatestJobs(20);
            context.append("**Aktuelle Jobs:**\n\n");
        }

        context.append(String.format("Gefunden: %d Jobs\n\n", jobs.size()));

        // Show job summaries (max 10)
        int shown = 0;
        for (Job job : jobs) {
            if (shown >= 10) {
                context.append(String.format("... und %d weitere Jobs\n", jobs.size() - 10));
                break;
            }
            context.append(
                    String.format("- %s: %s (%s)\n", job.getJobNumber() != null ? job.getJobNumber() : "Ohne Nr.",
                            job.getCustomerSelection() != null ? job.getCustomerSelection() : "Unbekannt",
                            job.getStatus().getDisplayName()));
            shown++;
        }

        return context.toString();
    }

    private String buildPrompt(String userQuery, String statisticsContext, QueryAnalysis analysis) {
        // User prompt contains only the context and question (system prompt is passed
        // separately)
        return String.format("""
                %s

                **Benutzerfrage:** %s
                """, statisticsContext, userQuery);
    }

    private String buildFallbackResponse(QueryAnalysis analysis) {
        String customer = analysis.customerFilter;
        JobStatus statusFilter = analysis.statusFilter;

        return switch (analysis.queryType) {
        case "list" -> {
            List<Job> jobs;
            if (customer != null && statusFilter != null) {
                jobs = statisticsService.getJobsByCustomerAndStatus(customer, statusFilter);
                yield String.format("Es wurden %d Jobs für %s mit Status \"%s\" gefunden.", jobs.size(), customer,
                        statusFilter.getDisplayName());
            } else if (customer != null) {
                jobs = statisticsService.getJobsByCustomer(customer);
                yield String.format("Es wurden %d Jobs für %s gefunden.", jobs.size(), customer);
            } else if (statusFilter != null) {
                jobs = statisticsService.getJobsByStatus(statusFilter);
                yield String.format("Es wurden %d Jobs mit Status \"%s\" gefunden.", jobs.size(),
                        statusFilter.getDisplayName());
            } else {
                yield "Hier sind die aktuellen Jobs.";
            }
        }
        case "status" -> {
            var counts = customer != null ? statisticsService.getJobCountsByStatusForCustomer(customer)
                    : statisticsService.getJobCountsByStatus();
            String title = customer != null ? String.format("**Auftragsübersicht für %s:**\n\n", customer)
                    : "**Auftragsübersicht nach Status:**\n\n";
            StringBuilder sb = new StringBuilder(title);
            counts.forEach((status, count) -> {
                if (count > 0) {
                    sb.append(String.format("- **%s:** %d Aufträge\n", status.getDisplayName(), count));
                }
            });
            long total = customer != null ? statisticsService.getTotalJobCountForCustomer(customer)
                    : statisticsService.getTotalJobCount();
            sb.append(String.format("\n**Gesamt:** %d Aufträge", total));
            yield sb.toString();
        }
        case "revenue" -> {
            if (customer != null) {
                var revenue = statisticsService.getTotalRevenueForCustomer(customer);
                var jobCount = statisticsService.getTotalJobCountForCustomer(customer);
                yield String.format("**Umsatz für %s:**\n\n" + "- **Gesamtumsatz:** %.2f EUR\n" + "- **Aufträge:** %d",
                        customer, revenue, jobCount);
            } else {
                var topCustomers = statisticsService.getTopCustomersByRevenue(5);
                StringBuilder sb = new StringBuilder("**Top Kunden nach Umsatz:**\n\n");
                int rank = 1;
                for (var entry : topCustomers) {
                    sb.append(String.format("%d. **%s:** %.2f EUR\n", rank++,
                            entry.getKey() != null ? entry.getKey() : "Unbekannt", entry.getValue()));
                }
                sb.append(String.format("\n**Gesamtumsatz:** %.2f EUR", statisticsService.getTotalRevenue()));
                yield sb.toString();
            }
        }
        case "trend" -> {
            int year = Year.now().getValue();
            var monthly = customer != null ? statisticsService.getMonthlyJobCountsForCustomer(year, customer)
                    : statisticsService.getMonthlyJobCounts(year);
            long total = monthly.values().stream().mapToLong(Long::longValue).sum();
            String title = customer != null ? String.format("**Monatstrend %d für %s:**", year, customer)
                    : String.format("**Monatstrend %d:**", year);
            yield String.format(
                    "%s\n\nInsgesamt wurden %d Aufträge erstellt. " + "Die Verteilung ist im Diagramm ersichtlich.",
                    title, total);
        }
        case "tasks" -> {
            var taskStats = statisticsService.getTaskCompletionStats();
            long total = taskStats.getOrDefault("total", 0L);
            long completed = taskStats.getOrDefault("completed", 0L);
            double rate = total > 0 ? (double) completed / total * 100 : 0;
            yield String.format("**Aufgabenstatistik:**\n\n" + "- **Gesamt:** %d Aufgaben\n"
                    + "- **Erledigt:** %d (%.1f%%)\n" + "- **Ausstehend:** %d", total, completed, rate,
                    taskStats.getOrDefault("pending", 0L));
        }
        default -> {
            if (customer != null) {
                yield String.format(
                        "**Übersicht für %s:**\n\n" + "- **Aufträge gesamt:** %d\n" + "- **Abschlussrate:** %.1f%%\n"
                                + "- **Umsatz:** %.2f EUR",
                        customer, statisticsService.getTotalJobCountForCustomer(customer),
                        statisticsService.getCompletionRateForCustomer(customer),
                        statisticsService.getTotalRevenueForCustomer(customer));
            } else {
                yield String.format(
                        "**Übersicht:**\n\n" + "- **Aufträge gesamt:** %d\n" + "- **Abschlussrate:** %.1f%%\n"
                                + "- **Gesamtumsatz:** %.2f EUR",
                        statisticsService.getTotalJobCount(), statisticsService.getCompletionRate(),
                        statisticsService.getTotalRevenue());
            }
        }
        };
    }
}
