package com.pharmacopoeia.service;

import com.pharmacopoeia.entity.UserEvent;
import com.pharmacopoeia.repository.UserEventRepository;
import jakarta.persistence.criteria.Predicate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class AnalyticsService {

    private static final Logger log = LoggerFactory.getLogger(AnalyticsService.class);
    private static final Instant FAR_FUTURE = Instant.parse("2099-12-31T23:59:59Z");

    private final UserEventRepository repo;
    private final JdbcTemplate jdbc;

    public AnalyticsService(UserEventRepository repo, JdbcTemplate jdbc) {
        this.repo = repo;
        this.jdbc = jdbc;
    }

    /** 默认来源系统：当前业务系统 */
    private static final String DEFAULT_SYSTEM = "AI药典";

    @Async("analyticsExecutor")
    public void saveEvent(
            final String userKey,
            final String eventType,
            @SuppressWarnings("rawtypes") final Map eventData,
            final String pageUrl,
            final String referrer,
            final String ip,
            final String userAgent,
            final String systemSource) {
        try {
            // Truncate data to avoid sql errors when user-agent is longer than the column, etc.
            UserEvent event = UserEvent.builder()
                    .userKey(trunc(userKey, 128))
                    .eventType(trunc(eventType, 64))
                    .eventData(eventData != null ? eventData : Map.of())
                    .pageUrl(trunc(pageUrl, 512))
                    .referrer(trunc(referrer, 512))
                    .ip(trunc(ip, 64))
                    .userAgent(trunc(userAgent, 512))
                    .systemSource(trunc(normalizeSystem(systemSource), 64))
                    .build();
            repo.save(event);
        } catch (Exception e) {
            log.warn("埋点写入失败: type={}, error={}", eventType, e.getMessage());
        }
    }

    /** 兼容旧调用方，默认归入 AI药典 系统 */
    public void saveEvent(
            final String userKey,
            final String eventType,
            @SuppressWarnings("rawtypes") final Map eventData,
            final String pageUrl,
            final String referrer,
            final String ip,
            final String userAgent) {
        saveEvent(userKey, eventType, eventData, pageUrl, referrer, ip, userAgent, DEFAULT_SYSTEM);
    }

    private static String normalizeSystem(String systemSource) {
        return (systemSource == null || systemSource.isBlank()) ? DEFAULT_SYSTEM : systemSource;
    }

    /**
     * 查询用系统过滤归一化：
     * null/空 → 默认 AI药典（只看本系统）；
     * "all"（大小写无关）→ null，表示跨系统全量统计；
     * 其它值 → 原样返回，按该系统过滤（如 "中医"）。
     */
    private static String normalizeSystemFilter(String systemSource) {
        if (systemSource == null || systemSource.isBlank()) return DEFAULT_SYSTEM;
        if ("all".equalsIgnoreCase(systemSource)) return null;
        return systemSource;
    }

    private static String trunc(String s, int max) {
        if (s == null) return null;
        return s.length() <= max ? s : s.substring(0, max);
    }

    // ==================== 埋点事件列表 ====================

    public Map<String, Object> queryEvents(String eventType, String systemSource,
                                           String startDate, String endDate,
                                           int page, int pageSize) {
        Instant startTime = parseDate(startDate) != null ? parseDate(startDate) : Instant.EPOCH;
        Instant endTime = endDate != null && !endDate.isBlank()
                ? LocalDate.parse(endDate).plusDays(1).atStartOfDay(ZoneOffset.UTC).toInstant()
                : FAR_FUTURE;

        Specification<UserEvent> spec = buildTimeSpec(eventType, normalizeSystemFilter(systemSource), startTime, endTime);
        var pageable = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Direction.DESC, "createdAt"));
        var result = repo.findAll(spec, pageable);

        List<Map<String, Object>> items = result.getContent().stream()
                .map(e -> {
                    Map<String, Object> m = new LinkedHashMap<>();
                    m.put("id", e.getId());
                    m.put("system", e.getSystemSource());
                    m.put("event_type", e.getEventType());
                    m.put("user_key", e.getUserKey());
                    m.put("page_url", e.getPageUrl());
                    m.put("ip", e.getIp());
                    m.put("created_at", e.getCreatedAt());
                    return m;
                })
                .collect(Collectors.toList());

        Map<String, Object> response = new LinkedHashMap<>();
        response.put("items", items);
        response.put("total", result.getTotalElements());
        response.put("page", page);
        response.put("page_size", pageSize);
        return response;
    }

    // ==================== 事件导出（CSV） ====================

    /** 单次导出上限：超出时提示用户缩小时间范围分批导出 */
    private static final int EXPORT_MAX_ROWS = 100_000;

    /** UTF-8 BOM，便于 Excel 直接双击打开时正确识别中文 */
    private static final byte[] CSV_BOM = new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF};

    /** 事件类型中文名映射，与前端 TrackingInfoView 的 EVENT_LABEL_MAP 对齐；未知类型保留原值 */
    private static final Map<String, String> EVENT_LABEL_MAP = Map.of(
            "page_view", "页面浏览",
            "search", "搜索",
            "click", "点击",
            "ai_qa", "AI问答",
            "chat", "AI问答"
    );

    private static final ZoneId BEIJING = ZoneId.of("Asia/Shanghai");
    private static final DateTimeFormatter EXPORT_TIME_FMT =
            DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(BEIJING);

    /** 导出结果：SUCCESS 返回 bytes；EMPTY/TOO_LARGE 返回面向用户的 message */
    public record EventExportResult(Status status, String message, byte[] bytes) {
        public enum Status { SUCCESS, EMPTY, TOO_LARGE }
    }

    /**
     * 按当前筛选条件全量导出埋点事件为 CSV（UTF-8 + BOM，便于 Excel 正确显示中文）。
     * 字段顺序：ID / 事件类型 / 来源系统 / 用户标识 / IP地址 / 时间，按时间倒序。
     * 事件类型取页面展示的中文名（与前端 getEventLabel 对齐）；时间为北京时间 yyyy-MM-dd HH:mm:ss。
     */
    public EventExportResult exportEvents(String eventType, String systemSource,
                                          String startDate, String endDate) {
        Instant startTime = parseDate(startDate) != null ? parseDate(startDate) : Instant.EPOCH;
        Instant endTime = endDate != null && !endDate.isBlank()
                ? LocalDate.parse(endDate).plusDays(1).atStartOfDay(ZoneOffset.UTC).toInstant()
                : FAR_FUTURE;
        String systemFilter = normalizeSystemFilter(systemSource);
        String typeFilter = (eventType == null || eventType.isBlank()) ? null : eventType;

        long total = repo.countForExport(startTime, endTime, systemFilter, typeFilter);
        if (total == 0) {
            return new EventExportResult(EventExportResult.Status.EMPTY, "当前筛选条件下无数据，无法导出", null);
        }
        if (total > EXPORT_MAX_ROWS) {
            return new EventExportResult(EventExportResult.Status.TOO_LARGE,
                    "当前筛选条件下数据量为 " + total + " 条，超过单次导出上限 " + EXPORT_MAX_ROWS
                            + " 条，请缩小时间范围后分批导出", null);
        }

        List<Object[]> rows = repo.findForExport(startTime, endTime, systemFilter, typeFilter);
        StringBuilder sb = new StringBuilder();
        sb.append("ID,事件类型,来源系统,用户标识,IP地址,时间\n");
        for (Object[] r : rows) {
            // r: [id, systemSource, eventType, userKey, ip, createdAt]
            sb.append(((Number) r[0]).longValue()).append(',')
                    .append(esc(mapEventLabel((String) r[2]))).append(',')
                    .append(esc((String) r[1])).append(',')
                    .append(esc((String) r[3])).append(',')
                    .append(esc((String) r[4])).append(',')
                    .append(esc(r[5] != null ? EXPORT_TIME_FMT.format((Instant) r[5]) : ""))
                    .append('\n');
        }
        byte[] content = sb.toString().getBytes(StandardCharsets.UTF_8);
        byte[] withBom = new byte[CSV_BOM.length + content.length];
        System.arraycopy(CSV_BOM, 0, withBom, 0, CSV_BOM.length);
        System.arraycopy(content, 0, withBom, CSV_BOM.length, content.length);
        return new EventExportResult(EventExportResult.Status.SUCCESS, "ok", withBom);
    }

    /** CSV 单元格转义：空值返回空串；非空则用双引号包裹并把内部双引号翻倍。与 BrandRecommendService#esc 对齐 */
    private static String esc(String s) {
        return (s == null || s.isEmpty()) ? "" : "\"" + s.replace("\"", "\"\"") + "\"";
    }

    /** 事件类型 → 页面展示中文名；未知类型保留原值，与前端 getEventLabel 一致 */
    private static String mapEventLabel(String type) {
        if (type == null) return "";
        return EVENT_LABEL_MAP.getOrDefault(type, type);
    }

    public Map<String, Object> getEventDetail(long id) {
        var opt = repo.findById(id);
        if (opt.isEmpty()) return Map.of();
        var e = opt.get();
        Map<String, Object> m = new LinkedHashMap<>();
        m.put("id", e.getId());
        m.put("system", e.getSystemSource());
        m.put("user_key", e.getUserKey());
        m.put("event_type", e.getEventType());
        m.put("event_data", e.getEventData());
        m.put("page_url", e.getPageUrl());
        m.put("referrer", e.getReferrer());
        m.put("ip", e.getIp());
        m.put("user_agent", e.getUserAgent());
        m.put("created_at", e.getCreatedAt());
        return m;
    }

    // ==================== 概览数字 ====================

    /**
     * 统计概览
     * @param range today | yesterday | week | total | custom
     * @param systemSource 来源系统：null/空 → 默认 AI药典；"all" → 跨系统全量；其它值 → 按该系统过滤
     * @param startDate custom 的起始日期（yyyy-MM-dd），仅 range=custom 时生效
     * @param endDate   custom 的结束日期（yyyy-MM-dd），仅 range=custom 时生效
     */
    public Map<String, Object> queryOverview(String range, String systemSource,
                                            String startDate, String endDate) {
        if (range == null || range.isBlank()) {
            range = "total";
        }
        String systemFilter = normalizeSystemFilter(systemSource);
        Instant todayStart = parseDate(LocalDate.now().toString());
        Instant todayEnd = LocalDate.now().plusDays(1).atStartOfDay(ZoneOffset.UTC).toInstant();

        Instant startTime;
        Instant endTime;
        String label;

        switch (range) {
            case "today":
                startTime = todayStart;
                endTime = todayEnd;
                label = "today";
                break;
            case "yesterday":
                startTime = todayStart.minus(1, java.time.temporal.ChronoUnit.DAYS);
                endTime = todayStart;
                label = "yesterday";
                break;
            case "week":
                startTime = todayStart.minus(6, java.time.temporal.ChronoUnit.DAYS);
                endTime = todayEnd;
                label = "week";
                break;
            case "custom":
                Instant customStart = startDate != null ? parseDate(startDate) : Instant.EPOCH;
                Instant customEnd = endDate != null
                        ? LocalDate.parse(endDate).plusDays(1).atStartOfDay(ZoneOffset.UTC).toInstant()
                        : FAR_FUTURE;
                startTime = customStart != null ? customStart : Instant.EPOCH;
                endTime = customEnd;
                label = "custom";
                break;
            default: // "total"
                startTime = Instant.EPOCH;
                endTime = FAR_FUTURE;
                label = "total";
        }

        Map<String, Object> overview = new LinkedHashMap<>();
        overview.put("range", label);
        overview.put("system", systemFilter != null ? systemFilter : "all");
        overview.put("total_events", repo.countTotal(startTime, endTime, systemFilter));
        overview.put("active_users", repo.countDistinctUsers(startTime, endTime, systemFilter));
        overview.put("unique_ips", repo.countDistinctIps(startTime, endTime, systemFilter));
        overview.put("page_views", repo.countByType("page_view", startTime, endTime, systemFilter));
        overview.put("searches", repo.countByType("search", startTime, endTime, systemFilter));
        overview.put("ai_qa", repo.countByType("chat", startTime, endTime, systemFilter));
        return overview;
    }

    // ==================== 维度分页统计 ====================

    /** 分页维度统计：ip / url / type / user / user_ip
     *  systemSource 来源系统：null/空 → 默认 AI药典；"all" → 跨系统全量；其它值 → 按该系统过滤 */
    public Map<String, Object> queryDimension(String dimension, String systemSource,
                                              String startDate, String endDate,
                                              int page, int pageSize) {
        Instant startTime = parseDate(startDate) != null ? parseDate(startDate) : Instant.EPOCH;
        Instant endTime = endDate != null && !endDate.isBlank()
                ? LocalDate.parse(endDate).plusDays(1).atStartOfDay(ZoneOffset.UTC).toInstant()
                : FAR_FUTURE;
        String systemFilter = normalizeSystemFilter(systemSource);

        Page<Object[]> result;
        switch (dimension != null ? dimension : "") {
            case "ip":
                result = repo.countByIpPaged(startTime, endTime, systemFilter,
                        PageRequest.of(page - 1, pageSize));
                break;
            case "url":
                result = repo.countByPageUrlPaged(startTime, endTime, systemFilter,
                        PageRequest.of(page - 1, pageSize));
                break;
            case "type":
                result = repo.countByEventTypePaged(startTime, endTime, systemFilter,
                        PageRequest.of(page - 1, pageSize));
                break;
            case "user":
                result = repo.countByUserKeyPaged(startTime, endTime, systemFilter,
                        PageRequest.of(page - 1, pageSize));
                break;
            case "user_ip":
                result = repo.countByUserIpPaged(startTime, endTime, systemFilter,
                        PageRequest.of(page - 1, pageSize));
                break;
            default:
                return Map.of();
        }

        List<Map<String, Object>> items = mapResult(result.getContent(), dimension);
        Map<String, Object> response = new LinkedHashMap<>();
        response.put("dimension", dimension);
        response.put("system", systemFilter != null ? systemFilter : "all");
        response.put("items", items);
        response.put("total", result.getTotalElements());
        response.put("page", page);
        response.put("page_size", pageSize);
        return response;
    }

    private List<Map<String, Object>> mapResult(List<Object[]> rows, String dimension) {
        return rows.stream()
                .map(row -> {
                    Map<String, Object> m = new LinkedHashMap<>();
                    if ("user_ip".equals(dimension)) {
                        m.put("user_key", row[0] != null ? row[0] : "");
                        m.put("ip", row[1] != null ? row[1] : "");
                        m.put("count", (Long) row[2]);
                    } else {
                        m.put("key", row[0] != null ? row[0] : "");
                        m.put("count", (Long) row[1]);
                    }
                    return m;
                })
                .collect(Collectors.toList());
    }


    // ==================== Event Types ====================

    /** Return all distinct event types for frontend switching */
    public List<String> getEventTypes() {
        return repo.findDistinctEventTypes();
    }

    /**
     * 返回当前所有出现过的来源系统，供前端系统切换下拉。
     * AI药典（本系统）恒定存在且排首位；其余按字母序追加。
     */
    public List<String> getSystems() {
        List<String> distinct = repo.findDistinctSystemSources();
        List<String> systems = new ArrayList<>();
        systems.add(DEFAULT_SYSTEM);
        for (String s : distinct) {
            if (!DEFAULT_SYSTEM.equals(s)) {
                systems.add(s);
            }
        }
        return systems;
    }

    // ==================== 问答会话（按 request_id 汇总耗时） ====================

    /**
     * 浏览每次 AI 问答的耗时：以 chat_complete 事件为主，LEFT JOIN chat（取 query）和
     * chat_stream_server（取服务端分段），按 request_id 关联，时间倒序分页。
     * systemSource: null/空 → AI药典；"all" → 跨系统；其它 → 按系统过滤。
     * minTotalMs: 只看耗时 ≥ 此值的（找慢请求），null/0 不过滤。
     */
    public Map<String, Object> queryQaSessions(String systemSource, String startDate, String endDate,
                                               int page, int pageSize, Long minTotalMs) {
        Instant startTime = parseDate(startDate) != null ? parseDate(startDate) : Instant.EPOCH;
        Instant endTime = endDate != null && !endDate.isBlank()
                ? LocalDate.parse(endDate).plusDays(1).atStartOfDay(ZoneOffset.UTC).toInstant()
                : FAR_FUTURE;
        String systemFilter = normalizeSystemFilter(systemSource);

        StringBuilder where = new StringBuilder(
                "WHERE c.event_type = 'chat_complete' AND c.created_at >= ? AND c.created_at < ?");
        List<Object> params = new ArrayList<>();
        params.add(startTime);
        params.add(endTime);
        if (systemFilter != null) {
            where.append(" AND c.system_source = ?");
            params.add(systemFilter);
        }
        if (minTotalMs != null && minTotalMs > 0) {
            where.append(" AND (c.event_data->>'total_ms')::bigint >= ?");
            params.add(minTotalMs);
        }

        Long total = jdbc.queryForObject(
                "SELECT COUNT(*) FROM user_events c " + where, Long.class, params.toArray());

        int offset = (page - 1) * pageSize;
        List<Object> dataParams = new ArrayList<>(params);
        dataParams.add(pageSize);
        dataParams.add(offset);
        String dataSql = "SELECT c.id, c.created_at, c.user_key, c.ip, "
                + "c.event_data->>'request_id' AS request_id, "
                + "q.event_data->>'query' AS query, "
                + "c.event_data->>'intent' AS intent, "
                + "c.event_data->>'status' AS status, "
                + "(c.event_data->>'total_ms')::bigint AS total_ms, "
                + "(c.event_data->>'ttft_ms')::bigint AS ttft_ms, "
                + "(c.event_data->>'msg_len')::int AS msg_len, "
                + "(c.event_data->>'has_media')::boolean AS has_media, "
                + "c.event_data->>'conversation_id' AS conversation_id, "
                + "s.event_data->>'endpoint' AS endpoint, "
                + "(s.event_data->>'total_ms')::bigint AS server_total_ms, "
                + "(s.event_data->>'search_rerank_ms')::bigint AS search_rerank_ms, "
                + "(s.event_data->>'prompt_ms')::bigint AS prompt_ms, "
                + "(s.event_data->>'llm_ms')::bigint AS llm_ms "
                + "FROM user_events c "
                + "LEFT JOIN user_events q ON q.event_type = 'chat' "
                + "  AND q.event_data->>'request_id' = c.event_data->>'request_id' "
                + "LEFT JOIN user_events s ON s.event_type = 'chat_stream_server' "
                + "  AND s.event_data->>'request_id' = c.event_data->>'request_id' "
                + where
                + " ORDER BY c.created_at DESC LIMIT ? OFFSET ?";

        List<Map<String, Object>> items = jdbc.queryForList(dataSql, dataParams.toArray());

        Map<String, Object> response = new LinkedHashMap<>();
        response.put("dimension", "qa_sessions");
        response.put("system", systemFilter != null ? systemFilter : "all");
        response.put("items", items);
        response.put("total", total);
        response.put("page", page);
        response.put("page_size", pageSize);
        return response;
    }

    // ==================== Helpers ====================

    private Specification<UserEvent> buildTimeSpec(String eventType, String systemSource,
                                                   Instant startTime, Instant endTime) {
        return (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();
            if (eventType != null && !eventType.isBlank()) {
                predicates.add(cb.equal(root.get("eventType"), eventType));
            }
            if (systemSource != null && !systemSource.isBlank()) {
                predicates.add(cb.equal(root.get("systemSource"), systemSource));
            }
            predicates.add(cb.greaterThanOrEqualTo(root.get("createdAt"), startTime));
            predicates.add(cb.lessThan(root.get("createdAt"), endTime));
            return cb.and(predicates.toArray(new Predicate[0]));
        };
    }

    private Instant parseDate(String date) {
        if (date == null || date.isBlank()) return null;
        return LocalDate.parse(date).atStartOfDay(ZoneOffset.UTC).toInstant();
    }
}
