package de.assecutor.votianlt.mcp.tools;

import de.assecutor.votianlt.mcp.dto.JobQueryResult;
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.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * MCP Tool for querying jobs with various filters.
 */
@Component
@Slf4j
public class JobQueryTool {

    private final JobStatisticsService statisticsService;

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

    @Tool(description = "Query jobs with optional filters. Returns a list of jobs matching the criteria.")
    public List<JobQueryResult> queryJobs(
            @ToolParam(description = "Optional: Job status filter (CREATED, IN_PROGRESS, PICKUP_SCHEDULED, PICKED_UP, IN_TRANSIT, DELIVERED, COMPLETED, CANCELLED)") String status,
            @ToolParam(description = "Optional: Customer name filter") String customer,
            @ToolParam(description = "Optional: Pickup city filter") String pickupCity,
            @ToolParam(description = "Optional: Delivery city filter") String deliveryCity,
            @ToolParam(description = "Maximum results to return (default 50)") Integer limit) {
        log.info("MCP Tool: Querying jobs with filters - status: {}, customer: {}, pickupCity: {}, deliveryCity: {}",
                status, customer, pickupCity, deliveryCity);

        int actualLimit = limit != null ? limit : 50;
        List<Job> jobs;

        if (status != null && !status.isBlank()) {
            JobStatus jobStatus = JobStatus.valueOf(status.toUpperCase());
            jobs = statisticsService.getJobsByStatus(jobStatus);
        } else if (customer != null && !customer.isBlank()) {
            jobs = statisticsService.getJobsByCustomer(customer);
        } else if (pickupCity != null && !pickupCity.isBlank()) {
            jobs = statisticsService.getJobsByPickupCity(pickupCity);
        } else if (deliveryCity != null && !deliveryCity.isBlank()) {
            jobs = statisticsService.getJobsByDeliveryCity(deliveryCity);
        } else {
            jobs = statisticsService.getLatestJobs(actualLimit);
        }

        return jobs.stream().limit(actualLimit).map(this::toQueryResult).toList();
    }

    @Tool(description = "Get detailed information about a specific job by its job number")
    public JobQueryResult getJobByNumber(
            @ToolParam(description = "The job number to look up (e.g., JOB-2024-0001)") String jobNumber) {
        log.info("MCP Tool: Getting job by number: {}", jobNumber);

        Job job = statisticsService.getJobByNumber(jobNumber);
        if (job == null) {
            return null;
        }
        return toQueryResult(job);
    }

    @Tool(description = "Get jobs assigned to a specific mobile app user")
    public List<JobQueryResult> getJobsByAppUser(@ToolParam(description = "App user identifier") String appUser) {
        log.info("MCP Tool: Getting jobs for app user: {}", appUser);

        return statisticsService.getJobsByAppUser(appUser).stream().map(this::toQueryResult).toList();
    }

    @Tool(description = "Get the most recent jobs, sorted by creation date descending")
    public List<JobQueryResult> getLatestJobs(
            @ToolParam(description = "Number of jobs to return (default 10)") Integer limit) {
        log.info("MCP Tool: Getting latest jobs, limit: {}", limit);

        int actualLimit = limit != null ? limit : 10;
        return statisticsService.getLatestJobs(actualLimit).stream().map(this::toQueryResult).toList();
    }

    @Tool(description = "Get jobs created within a specific date range")
    public List<JobQueryResult> getJobsByDateRange(
            @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,
            @ToolParam(description = "Maximum results to return (default 100)") Integer limit) {
        log.info("MCP Tool: Getting jobs for date range: {} to {}", startDate, endDate);

        LocalDateTime start = LocalDateTime.parse(startDate);
        LocalDateTime end = LocalDateTime.parse(endDate);
        int actualLimit = limit != null ? limit : 100;

        return statisticsService.getJobsByDateRange(start, end).stream().limit(actualLimit).map(this::toQueryResult)
                .toList();
    }

    private JobQueryResult toQueryResult(Job job) {
        return JobQueryResult.builder().jobId(job.getIdAsString()).jobNumber(job.getJobNumber())
                .status(job.getStatus() != null ? job.getStatus().name() : null)
                .statusDisplayName(job.getStatus() != null ? job.getStatus().getDisplayName() : null)
                .customer(job.getCustomerSelection()).pickupCity(job.getPickupCity())
                .deliveryCity(job.getDeliveryCity()).pickupDate(job.getPickupDate()).deliveryDate(job.getDeliveryDate())
                .price(job.getPrice()).createdAt(job.getCreatedAt()).assignedAppUser(job.getAppUser())
                .digitalProcessing(job.isDigitalProcessing()).build();
    }
}
