package com.lingniu.ingest.eventhistory;

import com.lingniu.ingest.tdenginehistory.TdengineHistoryReader;
import com.lingniu.ingest.tdenginehistory.TdengineLocationQuery;
import com.lingniu.ingest.tdenginehistory.TdengineLocationRow;
import com.lingniu.ingest.tdenginehistory.TdenginePage;
import com.lingniu.ingest.tdenginehistory.TdenginePageCursor;
import com.lingniu.ingest.tdenginehistory.TdengineQueryOrder;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;

import java.io.IOException;
import java.time.Instant;
import java.util.List;

@RestController
@ConditionalOnProperty(prefix = "lingniu.ingest.event-history", name = "enabled", havingValue = "true")
@ConditionalOnBean(TdengineHistoryReader.class)
@RequestMapping("/api/event-history")
@Tag(name = "location-history-controller", description = "通用位置历史分页查询接口。")
public final class LocationHistoryController {

    private final TdengineHistoryReader reader;

    public LocationHistoryController(TdengineHistoryReader reader) {
        if (reader == null) {
            throw new IllegalArgumentException("reader must not be null");
        }
        this.reader = reader;
    }

    @GetMapping("/locations")
    @Operation(
            summary = "查询车辆位置历史",
            description = "按协议、车辆标识和时间范围查询 TDengine 位置点。分页使用 cursorTs + cursorId，不使用 offset。")
    public LocationPageResponse locations(
            @Parameter(description = "协议名，例如 GB32960、JT808、MQTT_YUTONG。", required = true, example = "MQTT_YUTONG")
            @RequestParam String protocol,
            @Parameter(description = "内部车辆键。传入后优先使用。", example = "LMRKH9AC2R1004087")
            @RequestParam(required = false) String vehicleKey,
            @Parameter(description = "VIN。GB32960、宇通通常可直接用 VIN。", example = "LMRKH9AC2R1004087")
            @RequestParam(required = false) String vin,
            @Parameter(description = "JT808 终端手机号或终端标识；JT808 会自动映射为 jt808:<phone>。", example = "g7gps")
            @RequestParam(required = false) String phone,
            @Parameter(description = "开始时间，支持日期或精确到秒的时间；无时区时按东八区解析。", example = "2026-06-29T13:00:00")
            @RequestParam String dateFrom,
            @Parameter(description = "结束时间，支持日期或精确到秒的时间；无时区时按东八区解析。", example = "2026-06-29T13:10:00")
            @RequestParam String dateTo,
            @Parameter(description = "排序方向。", example = "DESC")
            @RequestParam(defaultValue = "DESC") TdengineQueryOrder order,
            @Parameter(description = "返回位置点数量上限，最大 1000。", example = "100")
            @RequestParam(defaultValue = "100") int limit,
            @Parameter(description = "上一页返回的 nextCursor.ts。", example = "2026-06-29T05:00:01Z")
            @RequestParam(required = false) String cursorTs,
            @Parameter(description = "上一页返回的 nextCursor.id。", example = "location-xxx")
            @RequestParam(required = false) String cursorId) throws IOException {
        String normalizedProtocol = DefaultProductionProtocols.requireSupported(
                require(protocol, "protocol is required for location query"));
        QueryTimeRange range = QueryTimeRange.parse(dateFrom, dateTo);
        TdenginePage<TdengineLocationRow> page = reader.queryLocations(new TdengineLocationQuery(
                normalizedProtocol,
                resolveVehicleKey(normalizedProtocol, vehicleKey, vin, phone),
                range.eventTimeFrom(),
                range.eventTimeTo().plusMillis(1),
                order,
                limit,
                cursor(cursorTs, cursorId)));
        return LocationPageResponse.from(page);
    }

    private static String resolveVehicleKey(String protocol, String vehicleKey, String vin, String phone) {
        String explicitVehicleKey = trimToNull(vehicleKey);
        if (explicitVehicleKey != null) {
            return explicitVehicleKey;
        }
        String vinValue = trimToNull(vin);
        if (vinValue != null) {
            return vinValue;
        }
        String phoneValue = trimToNull(phone);
        if (phoneValue != null) {
            if ("JT808".equals(protocol) && !phoneValue.startsWith("jt808:")) {
                return "jt808:" + phoneValue;
            }
            return phoneValue;
        }
        throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "vehicleKey, vin or phone is required");
    }

    private static String require(String value, String message) {
        String trimmed = trimToNull(value);
        if (trimmed == null) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, message);
        }
        return trimmed;
    }

    private static String trimToNull(String value) {
        if (value == null || value.isBlank()) {
            return null;
        }
        return value.trim();
    }

    private static TdenginePageCursor cursor(String cursorTs, String cursorId) {
        boolean hasTs = cursorTs != null && !cursorTs.isBlank();
        boolean hasId = cursorId != null && !cursorId.isBlank();
        if (!hasTs && !hasId) {
            return null;
        }
        if (!hasTs || !hasId) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "cursorTs and cursorId must be provided together");
        }
        return new TdenginePageCursor(Instant.parse(cursorTs.trim()), cursorId.trim());
    }

    public record LocationPageResponse(
            List<LocationResponse> items,
            CursorResponse nextCursor) {

        private static LocationPageResponse from(TdenginePage<TdengineLocationRow> page) {
            CursorResponse next = page.nextCursor()
                    .map(cursor -> new CursorResponse(cursor.ts().toString(), cursor.tieBreaker()))
                    .orElse(null);
            return new LocationPageResponse(
                    page.items().stream().map(LocationResponse::from).toList(),
                    next);
        }
    }

    public record CursorResponse(String ts, String id) {
    }

    public record LocationResponse(
            String eventTime,
            String receivedAt,
            String factId,
            String frameId,
            String phone,
            String vin,
            String vehicleKey,
            double longitude,
            double latitude,
            double altitudeM,
            double speedKmh,
            double directionDeg,
            long alarmFlag,
            long statusFlag,
            Double totalMileageKm,
            String rawUri,
            String protocol) {

        private static LocationResponse from(TdengineLocationRow row) {
            return new LocationResponse(
                    row.ts().toString(),
                    row.receivedAt().toString(),
                    row.factId(),
                    row.frameId(),
                    row.phone(),
                    row.vin(),
                    row.vehicleKey(),
                    row.longitude(),
                    row.latitude(),
                    row.altitudeM(),
                    row.speedKmh(),
                    row.directionDeg(),
                    row.alarmFlag(),
                    row.statusFlag(),
                    row.totalMileageKm(),
                    row.rawUri(),
                    row.protocol());
        }
    }
}
