package com.pharmacopoeia.controller;

import com.pharmacopoeia.config.QwenProperties;
import com.pharmacopoeia.config.AuthProperties;
import com.pharmacopoeia.dto.ApiResponse;
import com.pharmacopoeia.repository.DrugChunkRepository;
import com.pharmacopoeia.repository.DrugRepository;
import com.pharmacopoeia.repository.MessageRepository;
import com.pharmacopoeia.repository.UserRepository;
import com.pharmacopoeia.service.QACacheService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.LinkedHashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/v1/admin")
public class AdminController {

    private final QwenProperties qwenProperties;
    private final QACacheService qaCacheService;
    private final AuthProperties authProperties;
    private final DrugRepository drugRepo;
    private final DrugChunkRepository chunkRepo;
    private final MessageRepository msgRepo;
    private final UserRepository userRepo;

    public AdminController(QwenProperties qwenProperties,
                          QACacheService qaCacheService, AuthProperties authProperties,
                          DrugRepository drugRepo, DrugChunkRepository chunkRepo,
                          MessageRepository msgRepo, UserRepository userRepo) {
        this.qwenProperties = qwenProperties;
        this.qaCacheService = qaCacheService;
        this.authProperties = authProperties;
        this.drugRepo = drugRepo;
        this.chunkRepo = chunkRepo;
        this.msgRepo = msgRepo;
        this.userRepo = userRepo;
    }

    @GetMapping("/stats")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getStats() {
        long drugs = drugRepo.countByIsActiveTrue();
        long chunks = chunkRepo.countWithVector();
        long queries = msgRepo.countByRole("user");
        long users = userRepo.count();

        Map<String, Object> result = new LinkedHashMap<>();
        result.put("total_drugs", drugs);
        result.put("total_chunks", chunks);
        result.put("total_queries", queries);
        result.put("total_users", users);
        result.put("top_drugs", java.util.Collections.emptyList());
        result.put("daily_queries", java.util.Collections.emptyList());
        result.put("avg_response_time_ms", 0);
        return ResponseEntity.ok(ApiResponse.success(result));
    }

    @GetMapping("/feedback/list")
    public ResponseEntity<ApiResponse<Map<String, Object>>> listFeedback(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "20") int pageSize) {
        return ResponseEntity.ok(ApiResponse.success(Map.of(
                "items", java.util.Collections.emptyList(),
                "total", 0,
                "page", page,
                "page_size", pageSize
        )));
    }

    @GetMapping("/knowledge/status")
    public ResponseEntity<ApiResponse<Map<String, Object>>> knowledgeStatus() {
        long drugs = drugRepo.countByIsActiveTrue();
        long chunks = chunkRepo.countWithVector();
        Instant lastUpdate = drugRepo.findMaxUpdatedAt();

        Map<String, Object> result = new LinkedHashMap<>();
        result.put("total_drugs", drugs);
        result.put("total_chunks", chunks);
        result.put("last_update", lastUpdate != null ? lastUpdate.toString() : "");
        result.put("embedding_model", qwenProperties.getEmbeddingModel());
        return ResponseEntity.ok(ApiResponse.success(result));
    }

    @DeleteMapping("/cache")
    public ResponseEntity<ApiResponse<Map<String, Object>>> clearCache(
            @RequestParam(required = false) String keyword,
            @RequestHeader(value = "Authorization", required = false) String authHeader) {
        String adminToken = authProperties.getAdminToken();
        if (adminToken == null || adminToken.isBlank()) {
            return ResponseEntity.ok(
                    ApiResponse.<Map<String, Object>>builder().code(403).message("admin token 未配置").build());
        }
        boolean authorized = false;
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            String token = authHeader.substring(7);
            if (adminToken.equals(token)) {
                authorized = true;
            }
        }
        if (!authorized) {
            return ResponseEntity.ok(
                    ApiResponse.<Map<String, Object>>builder().code(403).message("仅运营端可操作").build());
        }
        int deleted = qaCacheService.clearAll(keyword);
        return ResponseEntity.ok(ApiResponse.success(Map.of("ok", true, "deleted", deleted)));
    }
}
