package com.example.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.sql.DataSource;
import java.sql.Connection;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;

/**
 * 健康检查控制器
 * 用于监控服务状态，无需认证
 */
@RestController
@RequestMapping("/api/health")
@Tag(name = "健康检查", description = "服务健康状态监控接口")
public class HealthCheckController {

    @Autowired
    private DataSource dataSource;

    /**
     * 健康检查接口
     * @return 服务健康状态
     */
    @GetMapping
    @Operation(summary = "健康检查", description = "检查服务运行状态、数据库连接等")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "服务正常"),
        @ApiResponse(responseCode = "503", description = "服务异常")
    })
    public ResponseEntity<Map<String, Object>> healthCheck() {
        Map<String, Object> health = new HashMap<>();
        boolean isHealthy = true;

        try {
            // 应用状态
            health.put("status", "UP");
            health.put("timestamp", LocalDateTime.now().toString());
            health.put("service", "AIGC Platform API");
            
            // 数据库连接检查
            Map<String, Object> database = new HashMap<>();
            try (Connection connection = dataSource.getConnection()) {
                boolean isValid = connection.isValid(5); // 5秒超时
                database.put("status", isValid ? "UP" : "DOWN");
                database.put("type", "MySQL");
                if (!isValid) {
                    isHealthy = false;
                }
            } catch (Exception e) {
                database.put("status", "DOWN");
                database.put("error", e.getMessage());
                isHealthy = false;
            }
            health.put("database", database);
            
            // 系统信息
            Map<String, Object> system = new HashMap<>();
            Runtime runtime = Runtime.getRuntime();
            system.put("availableProcessors", runtime.availableProcessors());
            system.put("totalMemory", runtime.totalMemory() / (1024 * 1024) + " MB");
            system.put("freeMemory", runtime.freeMemory() / (1024 * 1024) + " MB");
            system.put("maxMemory", runtime.maxMemory() / (1024 * 1024) + " MB");
            health.put("system", system);

            // 返回状态
            if (isHealthy) {
                return ResponseEntity.ok(health);
            } else {
                health.put("status", "DOWN");
                return ResponseEntity.status(503).body(health);
            }

        } catch (Exception e) {
            health.put("status", "DOWN");
            health.put("error", e.getMessage());
            return ResponseEntity.status(503).body(health);
        }
    }

    /**
     * 简单的健康检查（轻量级）
     * @return 简单的健康状态
     */
    @GetMapping("/ping")
    @Operation(summary = "简单健康检查", description = "快速检查服务是否在线")
    @ApiResponse(responseCode = "200", description = "服务在线")
    public ResponseEntity<Map<String, String>> ping() {
        Map<String, String> response = new HashMap<>();
        response.put("status", "OK");
        response.put("message", "pong");
        response.put("timestamp", LocalDateTime.now().toString());
        return ResponseEntity.ok(response);
    }

    /**
     * 就绪检查（Readiness Probe）
     * @return 服务是否就绪
     */
    @GetMapping("/ready")
    @Operation(summary = "就绪检查", description = "检查服务是否准备好处理请求")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "服务就绪"),
        @ApiResponse(responseCode = "503", description = "服务未就绪")
    })
    public ResponseEntity<Map<String, Object>> readiness() {
        Map<String, Object> readiness = new HashMap<>();
        boolean isReady = true;

        try {
            // 检查数据库连接
            try (Connection connection = dataSource.getConnection()) {
                if (!connection.isValid(5)) {
                    isReady = false;
                }
            } catch (Exception e) {
                isReady = false;
                readiness.put("error", "Database connection failed: " + e.getMessage());
            }

            readiness.put("ready", isReady);
            readiness.put("timestamp", LocalDateTime.now().toString());

            if (isReady) {
                return ResponseEntity.ok(readiness);
            } else {
                return ResponseEntity.status(503).body(readiness);
            }

        } catch (Exception e) {
            readiness.put("ready", false);
            readiness.put("error", e.getMessage());
            return ResponseEntity.status(503).body(readiness);
        }
    }

    /**
     * 存活检查（Liveness Probe）
     * @return 服务是否存活
     */
    @GetMapping("/live")
    @Operation(summary = "存活检查", description = "检查服务是否存活")
    @ApiResponse(responseCode = "200", description = "服务存活")
    public ResponseEntity<Map<String, Object>> liveness() {
        Map<String, Object> liveness = new HashMap<>();
        liveness.put("alive", true);
        liveness.put("timestamp", LocalDateTime.now().toString());
        return ResponseEntity.ok(liveness);
    }
}

