package de.assecutor.votianlt.mcp.tools;

import de.assecutor.votianlt.mcp.dto.CustomerRevenueResult;
import de.assecutor.votianlt.mcp.dto.JobStatisticsResult;
import de.assecutor.votianlt.model.JobStatus;
import de.assecutor.votianlt.service.JobStatisticsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.Month;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * MCP Tool for job statistics queries. Provides various statistics and
 * aggregations about jobs.
 */
@Component
@Slf4j
public class JobStatisticsTool {

    private final JobStatisticsService statisticsService;

    public JobStatisticsTool(JobStatisticsService statisticsService) {
        this.statisticsService = statisticsService;
    }

    @Tool(description = "Get comprehensive job statistics including counts by status, completion rates, and revenue metrics")
    public JobStatisticsResult getJobStatistics() {
        log.info("MCP Tool: Getting job statistics");

        Map<JobStatus, Long> countsByStatus = statisticsService.getJobCountsByStatus();
        Map<String, Long> statusCounts = countsByStatus.entrySet().stream()
                .collect(Collectors.toMap(e -> e.getKey().name(), Map.Entry::getValue));

        long completed = countsByStatus.getOrDefault(JobStatus.COMPLETED, 0L);
        long cancelled = countsByStatus.getOrDefault(JobStatus.CANCELLED, 0L);
        long inProgress = countsByStatus.getOrDefault(JobStatus.IN_PROGRESS, 0L);

        return JobStatisticsResult.builder().countsByStatus(statusCounts)
                .totalJobs(statisticsService.getTotalJobCount()).completedJobs(completed).cancelledJobs(cancelled)
                .inProgressJobs(inProgress).completionRate(statisticsService.getCompletionRate())
                .totalRevenue(statisticsService.getTotalRevenue()).queryTimestamp(LocalDateTime.now()).build();
    }

    @Tool(description = "Get job counts grouped by status (CREATED, IN_PROGRESS, PICKUP_SCHEDULED, PICKED_UP, IN_TRANSIT, DELIVERED, COMPLETED, CANCELLED)")
    public Map<String, Long> getJobCountsByStatus() {
        log.info("MCP Tool: Getting job counts by status");

        Map<JobStatus, Long> counts = statisticsService.getJobCountsByStatus();
        return counts.entrySet().stream().collect(Collectors
                .toMap(e -> e.getKey().name() + " (" + e.getKey().getDisplayName() + ")", Map.Entry::getValue));
    }

    @Tool(description = "Get the completion rate as a percentage (completed jobs / total jobs * 100)")
    public String getCompletionRate() {
        log.info("MCP Tool: Getting completion rate");

        double rate = statisticsService.getCompletionRate();
        return String.format("%.2f%%", rate);
    }

    @Tool(description = "Get revenue statistics grouped by customer, sorted by revenue descending")
    public List<CustomerRevenueResult> getRevenueByCustomer(
            @ToolParam(description = "Maximum number of customers to return (default 10)") Integer limit) {
        log.info("MCP Tool: Getting revenue by customer, limit: {}", limit);

        int actualLimit = limit != null ? limit : 10;
        return statisticsService.getTopCustomersByRevenue(actualLimit).stream().map(entry -> {
            String customer = entry.getKey();
            long jobCount = statisticsService.getJobsByCustomer(customer).size();
            return CustomerRevenueResult.builder().customer(customer).revenue(entry.getValue()).jobCount(jobCount)
                    .build();
        }).toList();
    }

    @Tool(description = "Get monthly job trend data for a specific year showing job counts per month")
    public Map<String, Long> getMonthlyJobTrend(
            @ToolParam(description = "Year for the trend data (e.g., 2024)") int year) {
        log.info("MCP Tool: Getting monthly job trend for year: {}", year);

        Map<Month, Long> monthlyData = statisticsService.getMonthlyJobCounts(year);
        return monthlyData.entrySet().stream()
                .collect(Collectors.toMap(e -> e.getKey().toString(), Map.Entry::getValue));
    }

    @Tool(description = "Get total revenue from all jobs")
    public String getTotalRevenue() {
        log.info("MCP Tool: Getting total revenue");

        BigDecimal revenue = statisticsService.getTotalRevenue();
        return String.format("%.2f EUR", revenue);
    }

    @Tool(description = "Get job count for a specific date range")
    public long getJobCountByDateRange(
            @ToolParam(description = "Start date in ISO format (e.g., 2024-01-01T00:00:00)") String startDate,
            @ToolParam(description = "End date in ISO format (e.g., 2024-12-31T23:59:59)") String endDate) {
        log.info("MCP Tool: Getting job count for date range: {} to {}", startDate, endDate);

        LocalDateTime start = LocalDateTime.parse(startDate);
        LocalDateTime end = LocalDateTime.parse(endDate);
        return statisticsService.getJobCountByDateRange(start, end);
    }
}
