package com.xy.xyaicpzs.controller;

import com.xy.xyaicpzs.common.ErrorCode;
import com.xy.xyaicpzs.common.ResultUtils;
import com.xy.xyaicpzs.common.response.ApiResponse;
import com.xy.xyaicpzs.domain.vo.SSQFirstStepResultVO;
import com.xy.xyaicpzs.domain.vo.SSQSecondStepResultVO;
import com.xy.xyaicpzs.domain.vo.SSQThirdStepResultVO;
import com.xy.xyaicpzs.jt.jtssq.FirstBallAnalysis;
import com.xy.xyaicpzs.jt.jtssq.FollowBallAnalysis;
import com.xy.xyaicpzs.jt.jtssq.BlueBallAnalysis;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/jtssq/analysis")
@Tag(name = "精推双色球分析", description = "精推双色球三步分析算法API")
public class JtSsqCotroller {
    
    @Autowired
    private FirstBallAnalysis firstBallAnalysis;
    
    @Autowired
    private FollowBallAnalysis followBallAnalysis;
    
    @Autowired
    private BlueBallAnalysis blueBallAnalysis;
    
    /**
     * 精推双色球第一步分析
     */
    @PostMapping("/first-step")
    @Operation(summary = "精推双色球第一步分析", description = "根据红球和蓝球号码进行第一步分析")
    public ApiResponse<SSQFirstStepResultVO> firstStepAnalysis(
            @Parameter(description = "策略级别（H-高位/M-中位/L-低位）", required = true)
            @RequestParam String level,
            @Parameter(description = "红球号码列表（逗号分隔，如：1,5,12,18,22,30）", required = true)
            @RequestParam String redBalls,
            @Parameter(description = "蓝球号码", required = true)
            @RequestParam Integer blueBall) {
        
        try {
            // 参数验证
            if (!"H".equalsIgnoreCase(level) && !"M".equalsIgnoreCase(level) && !"L".equalsIgnoreCase(level)) {
                return ResultUtils.error(ErrorCode.PARAMS_ERROR, "策略级别必须是H/M/L之一");
            }
            
            if (blueBall == null || blueBall < 1 || blueBall > 16) {
                return ResultUtils.error(ErrorCode.PARAMS_ERROR, "蓝球号码范围应为1-16");
            }
            
            // 解析红球号码
            String[] redBallArray = redBalls.split(",");
            if (redBallArray.length != 6) {
                return ResultUtils.error(ErrorCode.PARAMS_ERROR, "红球号码必须为6个");
            }
            
            List<Integer> redBallList = java.util.Arrays.stream(redBallArray)
                    .map(s -> {
                        try {
                            int ball = Integer.parseInt(s.trim());
                            if (ball < 1 || ball > 33) {
                                throw new IllegalArgumentException("红球号码范围应为1-33");
                            }
                            return ball;
                        } catch (NumberFormatException e) {
                            throw new IllegalArgumentException("红球号码格式错误");
                        }
                    })
                    .collect(java.util.stream.Collectors.toList());
            
            log.info("精推双色球第一步分析请求：策略={}, 红球={}, 蓝球={}", level, redBallList, blueBall);
            
            // 调用分析算法
            SSQFirstStepResultVO result = firstBallAnalysis.analyze(level, redBallList, blueBall);
            
            log.info("精推双色球第一步分析完成，返回{}个结果", result.getResults().size());
            
            return ResultUtils.success(result);
            
        } catch (Exception e) {
            log.error("精推双色球第一步分析失败", e);
            return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "分析失败：" + e.getMessage());
        }
    }
    
    /**
     * 精推双色球第二步分析
     */
    @PostMapping("/second-step")
    @Operation(summary = "精推双色球第二步分析", description = "根据红球、蓝球和下期首球号码进行第二步分析")
    public ApiResponse<SSQSecondStepResultVO> secondStepAnalysis(
            @Parameter(description = "策略级别（H-高位/M-中位/L-低位）", required = true)
            @RequestParam String level,
            @Parameter(description = "红球号码列表（逗号分隔，如：1,5,12,18,22,30）", required = true)
            @RequestParam String redBalls,
            @Parameter(description = "蓝球号码", required = true)
            @RequestParam Integer blueBall,
            @Parameter(description = "下期首球号码", required = true)
            @RequestParam Integer nextFirstBall) {
        
        try {
            // 参数验证
            if (!"H".equalsIgnoreCase(level) && !"M".equalsIgnoreCase(level) && !"L".equalsIgnoreCase(level)) {
                return ResultUtils.error(ErrorCode.PARAMS_ERROR, "策略级别必须是H/M/L之一");
            }
            
            if (blueBall == null || blueBall < 1 || blueBall > 16) {
                return ResultUtils.error(ErrorCode.PARAMS_ERROR, "蓝球号码范围应为1-16");
            }
            
            if (nextFirstBall == null || nextFirstBall < 1 || nextFirstBall > 33) {
                return ResultUtils.error(ErrorCode.PARAMS_ERROR, "下期首球号码范围应为1-33");
            }
            
            // 解析红球号码
            String[] redBallArray = redBalls.split(",");
            if (redBallArray.length != 6) {
                return ResultUtils.error(ErrorCode.PARAMS_ERROR, "红球号码必须为6个");
            }
            
            List<Integer> redBallList = java.util.Arrays.stream(redBallArray)
                    .map(s -> {
                        try {
                            int ball = Integer.parseInt(s.trim());
                            if (ball < 1 || ball > 33) {
                                throw new IllegalArgumentException("红球号码范围应为1-33");
                            }
                            return ball;
                        } catch (NumberFormatException e) {
                            throw new IllegalArgumentException("红球号码格式错误");
                        }
                    })
                    .collect(java.util.stream.Collectors.toList());
            
            log.info("精推双色球第二步分析请求：策略={}, 红球={}, 蓝球={}, 下期首球={}", 
                    level, redBallList, blueBall, nextFirstBall);
            
            // 调用分析算法
            SSQSecondStepResultVO result = followBallAnalysis.analyze(level, redBallList, blueBall, nextFirstBall);
            
            log.info("精推双色球第二步分析完成，返回{}个结果", result.getResults().size());
            
            return ResultUtils.success(result);
            
        } catch (Exception e) {
            log.error("精推双色球第二步分析失败", e);
            return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "分析失败：" + e.getMessage());
        }
    }
    
    /**
     * 精推双色球第三步分析
     */
    @PostMapping("/third-step")
    @Operation(summary = "精推双色球第三步分析", description = "根据红球、蓝球和下期红球号码进行第三步分析")
    public ApiResponse<SSQThirdStepResultVO> thirdStepAnalysis(
            @Parameter(description = "策略级别（H-高位/M-中位/L-低位）", required = true)
            @RequestParam String level,
            @Parameter(description = "红球号码列表（逗号分隔，如：1,5,12,18,22,30）", required = true)
            @RequestParam String redBalls,
            @Parameter(description = "蓝球号码", required = true)
            @RequestParam Integer blueBall,
            @Parameter(description = "下期红球号码列表（逗号分隔，如：2,9,16,23,29,32）", required = true)
            @RequestParam String nextRedBalls) {
        
        try {
            // 参数验证
            if (!"H".equalsIgnoreCase(level) && !"M".equalsIgnoreCase(level) && !"L".equalsIgnoreCase(level)) {
                return ResultUtils.error(ErrorCode.PARAMS_ERROR, "策略级别必须是H/M/L之一");
            }
            
            if (blueBall == null || blueBall < 1 || blueBall > 16) {
                return ResultUtils.error(ErrorCode.PARAMS_ERROR, "蓝球号码范围应为1-16");
            }
            
            // 解析红球号码
            String[] redBallArray = redBalls.split(",");
            if (redBallArray.length != 6) {
                return ResultUtils.error(ErrorCode.PARAMS_ERROR, "红球号码必须为6个");
            }
            
            List<Integer> redBallList = java.util.Arrays.stream(redBallArray)
                    .map(s -> {
                        try {
                            int ball = Integer.parseInt(s.trim());
                            if (ball < 1 || ball > 33) {
                                throw new IllegalArgumentException("红球号码范围应为1-33");
                            }
                            return ball;
                        } catch (NumberFormatException e) {
                            throw new IllegalArgumentException("红球号码格式错误");
                        }
                    })
                    .collect(java.util.stream.Collectors.toList());
            
            // 解析下期红球号码
            String[] nextRedBallArray = nextRedBalls.split(",");
            if (nextRedBallArray.length != 6) {
                return ResultUtils.error(ErrorCode.PARAMS_ERROR, "下期红球号码必须为6个");
            }
            
            List<Integer> nextRedBallList = java.util.Arrays.stream(nextRedBallArray)
                    .map(s -> {
                        try {
                            int ball = Integer.parseInt(s.trim());
                            if (ball < 1 || ball > 33) {
                                throw new IllegalArgumentException("下期红球号码范围应为1-33");
                            }
                            return ball;
                        } catch (NumberFormatException e) {
                            throw new IllegalArgumentException("下期红球号码格式错误");
                        }
                    })
                    .collect(java.util.stream.Collectors.toList());
            
            log.info("精推双色球第三步分析请求：策略={}, 红球={}, 蓝球={}, 下期红球={}", 
                    level, redBallList, blueBall, nextRedBallList);
            
            // 调用分析算法
            SSQThirdStepResultVO result = blueBallAnalysis.analyze(level, redBallList, blueBall, nextRedBallList);
            
            log.info("精推双色球第三步分析完成，返回{}个结果", result.getResults().size());
            
            return ResultUtils.success(result);
            
        } catch (Exception e) {
            log.error("精推双色球第三步分析失败", e);
            return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "分析失败：" + e.getMessage());
        }
    }
}
