package com.lingniu.ingest.eventhistory;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lingniu.ingest.tdenginehistory.TdengineHistoryReader;
import com.lingniu.ingest.tdenginehistory.TdenginePage;
import com.lingniu.ingest.tdenginehistory.TdenginePageCursor;
import com.lingniu.ingest.tdenginehistory.TdengineQueryOrder;
import com.lingniu.ingest.tdenginehistory.TdengineRawFrameQuery;
import com.lingniu.ingest.tdenginehistory.TdengineRawFrameRow;
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.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

@RestController
@ConditionalOnProperty(prefix = "lingniu.ingest.event-history", name = "enabled", havingValue = "true")
@ConditionalOnBean(TdengineHistoryReader.class)
@RequestMapping("/api/event-history")
@Tag(name = "Raw Frame API", description = "原始帧索引分页查询接口。")
public final class RawFrameHistoryController {

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
    private static final TypeReference<Map<String, Object>> MAP_TYPE = new TypeReference<>() {};
    private final TdengineHistoryReader reader;

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

    @GetMapping("/raw-frames")
    @Operation(
            summary = "查询原始帧索引",
            description = "按 protocol、vehicleKey、VIN、phone、messageId、parseStatus 和时间范围查询 TDengine raw_frames。"
                    + "返回 metadataJson 与 rawUri，分页使用 cursorTs + cursorId。")
    public RawFramePageResponse rawFrames(
            @Parameter(description = "协议类型，例如 GB32960、JT808、MQTT_YUTONG。", example = "JT808")
            @RequestParam String protocol,
            @Parameter(description = "内部车辆键；传入后精确过滤 vehicle_key。", example = "jt808:g7gps")
            @RequestParam(required = false) String vehicleKey,
            @Parameter(description = "VIN。已完成身份反写的 raw 帧可用该字段查询。", example = "LB9A32A24P0LS1270")
            @RequestParam(required = false) String vin,
            @Parameter(description = "终端手机号或终端标识，主要用于 JT808。", example = "g7gps")
            @RequestParam(required = false) String phone,
            @Parameter(description = "消息 ID，支持十进制或 0x 十六进制，例如 512 或 0x0200。", example = "0x0200")
            @RequestParam(required = false) String messageId,
            @Parameter(description = "解析状态，例如 SUCCEEDED、FAILED、NOT_PARSED。", example = "SUCCEEDED")
            @RequestParam(required = false) String parseStatus,
            @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 = "frame-xxx")
            @RequestParam(required = false) String cursorId) throws IOException {
        Integer parsedMessageId = parseMessageId(messageId);
        if (allBlank(vehicleKey, vin, phone) && parsedMessageId == null && isBlank(parseStatus)) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST,
                    "vehicleKey, vin, phone, messageId or parseStatus is required for raw frame query");
        }
        String normalizedProtocol = DefaultProductionProtocols.requireSupported(protocol);
        QueryTimeRange range = QueryTimeRange.parse(dateFrom, dateTo);
        TdenginePage<TdengineRawFrameRow> page = reader.queryRawFrames(new TdengineRawFrameQuery(
                normalizedProtocol,
                normalize(vehicleKey),
                normalize(vin),
                normalize(phone),
                parsedMessageId,
                normalize(parseStatus).toUpperCase(Locale.ROOT),
                range.eventTimeFrom(),
                range.eventTimeTo().plusMillis(1),
                order,
                limit,
                cursor(cursorTs, cursorId)));
        return RawFramePageResponse.from(page);
    }

    private static Integer parseMessageId(String messageId) {
        String value = normalize(messageId);
        if (value.isBlank()) {
            return null;
        }
        try {
            if (value.startsWith("0x") || value.startsWith("0X")) {
                return Integer.parseInt(value.substring(2), 16);
            }
            return Integer.valueOf(value);
        } catch (NumberFormatException ex) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "messageId must be decimal or 0x hex", ex);
        }
    }

    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());
    }

    private static boolean allBlank(String... values) {
        for (String value : values) {
            if (!isBlank(value)) {
                return false;
            }
        }
        return true;
    }

    private static boolean isBlank(String value) {
        return value == null || value.isBlank();
    }

    private static String normalize(String value) {
        return value == null ? "" : value.trim();
    }

    public record RawFramePageResponse(
            List<RawFrameResponse> items,
            CursorResponse nextCursor) {

        private static RawFramePageResponse from(TdenginePage<TdengineRawFrameRow> page) {
            CursorResponse next = page.nextCursor()
                    .map(cursor -> new CursorResponse(cursor.ts().toString(), cursor.tieBreaker()))
                    .orElse(null);
            List<RawFrameResponse> items = new java.util.ArrayList<>(page.items().size());
            for (TdengineRawFrameRow row : page.items()) {
                items.add(RawFrameResponse.from(row));
            }
            return new RawFramePageResponse(
                    items,
                    next);
        }
    }

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

    public record RawFrameResponse(
            String eventTime,
            String receivedAt,
            String frameId,
            int messageId,
            String messageIdHex,
            int subType,
            String rawUri,
            String checksum,
            long rawSizeBytes,
            String parseStatus,
            String parseError,
            String peer,
            String metadataJson,
            String parsedJson,
            Map<String, Object> metadata,
            Map<String, Object> parsedFields,
            String protocol,
            String vehicleKey,
            String vin,
            String phone) {

        private static RawFrameResponse from(TdengineRawFrameRow row) {
            Map<String, Object> metadata = metadata(row.metadataJson());
            return new RawFrameResponse(
                    row.ts().toString(),
                    row.receivedAt().toString(),
                    row.frameId(),
                    row.messageId(),
                    "0x%04X".formatted(row.messageId()),
                    row.subType(),
                    row.rawUri(),
                    row.checksum(),
                    row.rawSizeBytes(),
                    row.parseStatus(),
                    row.parseError(),
                    row.peer(),
                    row.metadataJson(),
                    row.parsedJson(),
                    metadata,
                    parsedFields(metadata, parsed(row.parsedJson())),
                    row.protocol(),
                    row.vehicleKey(),
                    row.vin(),
                    row.phone());
        }

        private static Map<String, Object> metadata(String metadataJson) {
            if (metadataJson == null || metadataJson.isBlank()) {
                return Map.of();
            }
            try {
                return OBJECT_MAPPER.readValue(metadataJson, MAP_TYPE);
            } catch (Exception ignored) {
                return Map.of("_raw", metadataJson);
            }
        }

        private static Map<String, Object> parsedFields(Map<String, Object> metadata,
                                                        Map<String, Object> parsed) {
            Map<String, Object> out = new LinkedHashMap<>();
            if (parsed.isEmpty()) {
                for (Map.Entry<String, Object> entry : metadata.entrySet()) {
                    String key = entry.getKey();
                    if (key == null || key.isBlank()) {
                        continue;
                    }
                    if (key.startsWith("raw.") || key.startsWith("jt808.")) {
                        out.put(key, entry.getValue());
                    } else {
                        out.put("raw." + key, entry.getValue());
                    }
                }
            } else {
                out.putAll(parsed);
            }
            return immutableMap(out);
        }

        private static Map<String, Object> parsed(String parsedJson) {
            if (parsedJson == null || parsedJson.isBlank()) {
                return Map.of();
            }
            try {
                return OBJECT_MAPPER.readValue(parsedJson, MAP_TYPE);
            } catch (Exception ignored) {
                return Map.of("_raw", parsedJson);
            }
        }

        private static Map<String, Object> immutableMap(Map<String, Object> values) {
            return Collections.unmodifiableMap(new LinkedHashMap<>(values));
        }
    }

}
