package com.rj.controller;

import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;


import java.lang.System;
import java.util.Collections;
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.aigc.generation.TranslationOptions;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import org.springframework.web.multipart.MultipartFile;


/**
 * 翻译、法律、意图理解控制器
 * 
 * @author 李中华
 * @date 2025/1/3
 */
@Slf4j
@RestController
@RequestMapping("/api/translation")
@Tag(name = "文本模型AI服务", description = "翻译、法律咨询、意图理解API接口")
public class TextModelController {

    /**
     * 翻译请求DTO
     */
    @Data
    public static class TranslationRequest {
        @NotBlank(message = "原语言文字不能为空")
        private String sourceText;
        
        @NotBlank(message = "目标语言不能为空")
        private String targetLanguage;
        
        @NotBlank(message = "原语言不能为空")
        private String sourceLanguage;
        @NotBlank(message = "大模型名称")
        private String model;
    }

    /**
     * 法律咨询请求DTO
     */
    @Data
    public static class LegalRequest {
        @NotBlank(message = "咨询目的不能为空")
        private String consultationPurpose;
        
        @NotBlank(message = "咨询类型不能为空")
        private String consultationType;
        
        @NotBlank(message = "核心诉求不能为空")
        private String coreDemand;
        
        @NotBlank(message = "咨询详细内容不能为空")
        private String inputText;
        
        @NotBlank(message = "大模型名称不能为空")
        private String model;
    }

    /**
     * 意图理解请求DTO
     */
    @Data
    public static class IntentRequest {
        @NotBlank(message = "输入文本不能为空")
        private String text;
        
        private String context;
        private String domain;
        @NotBlank(message = "大模型名称")
        private String model;
    }

    /**
     * 参考边缘信息DTO
     */
    @Data
    public static class ReferenceEdge {
        private String[] foregroundEdge;
        private String[] backgroundEdge;
        private String[] foregroundEdgePrompt;
        private String[] backgroundEdgePrompt;
    }

    /**
     * 参数配置DTO
     */
    @Data
    public static class Parameters {
        private Integer n = 1;
        private Double refPromptWeight = 0.5;
        private String modelVersion = "v3";
    }

    /**
     * 图像处理请求DTO
     */
    @Data
    public static class ImageProcessingRequest {
        @NotBlank(message = "基础图片URL不能为空")
        private String baseImageUrl;
        
        @NotBlank(message = "参考图片URL不能为空")
        private String refImageUrl;

        //上传的文件
        private MultipartFile multipartFile;


        @NotBlank(message = "参考提示词不能为空")
        private String refPrompt;

        @NotBlank(message = "所属人姓名。")
        private String ownerName;

        @NotBlank(message = "所属人电话")
        private String ownerPhone;

        @NotBlank(message = "图片名称")
        private String imageName;

        @NotBlank(message = "提示词")
        private String prompt;

        @NotBlank(message = "模型")
        private String model;

        private ReferenceEdge referenceEdge;
        private Parameters parameters;
    }

    /**
     * 翻译接口
     */
    @PostMapping("/translate")
    @Operation(summary = "文本翻译", description = "将文本从源语言翻译到目标语言")
    public ResponseEntity<Map<String, Object>> translate(
            @Parameter(description = "翻译请求参数") @Valid @RequestBody TranslationRequest request) {
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            log.info("开始翻译，模型: {}, 目标语言: {}, 文本长度: {}",
                request.getModel(), request.getTargetLanguage(), request.getSourceText().length());
            
            // 模拟翻译处理（实际项目中应该调用翻译服务）
            String translatedText = performTranslation(
                request.getSourceText(), 
                request.getModel(),
                request.getTargetLanguage()
            );
            
            result.put("success", true);
            result.put("message", "翻译成功");
            result.put("sourceText", request.getSourceText());
            result.put("translatedText", translatedText);
            result.put("sourceLanguage", request.getSourceLanguage());
            result.put("targetLanguage", request.getTargetLanguage());
            result.put("translationConfidence", 0.95);
            result.put("processingTimeMs", 1200);
            result.put("requestId", generateRequestId());
            result.put("timestamp", LocalDateTime.now());
            
            log.info("翻译完成，目标文本长度: {}", translatedText.length());
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            log.error("翻译失败: {}", e.getMessage(), e);
            result.put("success", false);
            result.put("message", "翻译失败: " + e.getMessage());
            result.put("error", e.getClass().getSimpleName());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }

    /**
     * 法律咨询接口
     */
    @PostMapping("/legal")
    @Operation(summary = "法律咨询", description = "提供法律问题咨询和建议")
    public ResponseEntity<Map<String, Object>> legalConsultation(
            @Parameter(description = "法律咨询请求参数") @Valid @RequestBody LegalRequest request) {
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            log.info("开始法律咨询，咨询目的: {}, 咨询类型: {}, 核心诉求: {}, 内容长度: {}", 
                request.getConsultationPurpose(), request.getConsultationType(), 
                request.getCoreDemand(), request.getInputText().length());
            
            // 模拟法律咨询处理（实际项目中应该调用AI法律服务）
            Map<String, Object> legalResponse = performLegalConsultation(request);
            
            result.put("success", true);
            result.put("message", "法律咨询完成");
            result.put("answer", legalResponse.get("answer"));
            result.put("inputContent", request.getInputText());
            
            log.info("法律咨询完成，回答长度: {}", legalResponse.get("answer").toString().length());
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            log.error("法律咨询失败: {}", e.getMessage(), e);
            result.put("success", false);
            result.put("message", "法律咨询失败: " + e.getMessage());
            result.put("error", e.getClass().getSimpleName());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }

    /**
     * 意图理解接口
     */
    @PostMapping("/intent")
    @Operation(summary = "意图理解", description = "分析文本的意图和情感")
    public ResponseEntity<Map<String, Object>> intentAnalysis(
            @Parameter(description = "意图理解请求参数") @Valid @RequestBody IntentRequest request) {
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            log.info("开始意图分析，领域: {}, 上下文: {}, 文本长度: {}", 
                request.getDomain(), request.getContext(), request.getText().length());
            
            // 模拟意图理解处理（实际项目中应该调用NLP服务）
            Map<String, Object> intentResponse = performIntentAnalysis(request);
            
            result.put("success", true);
            result.put("message", "意图分析完成");
            result.put("text", request.getText());
            result.put("intent", intentResponse.get("intent"));
            result.put("confidence", intentResponse.get("confidence"));
            result.put("entities", intentResponse.get("entities"));
            result.put("sentiment", intentResponse.get("sentiment"));
            result.put("emotion", intentResponse.get("emotion"));
            result.put("domain", intentResponse.get("domain"));
            result.put("processingTimeMs", 800);
            result.put("requestId", generateRequestId());
            result.put("timestamp", LocalDateTime.now());
            
            log.info("意图分析完成，识别意图: {}", intentResponse.get("intent"));
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            log.error("意图分析失败: {}", e.getMessage(), e);
            result.put("success", false);
            result.put("message", "意图分析失败: " + e.getMessage());
            result.put("error", e.getClass().getSimpleName());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }


    /**
     * 执行翻译的模拟方法
     */
    private String performTranslation(String sourceText, String model, String targetLanguage) {

        Generation gen = new Generation();
        Message userMsg = Message.builder()
                .role(Role.USER.getValue())
                .content(sourceText)
                .build();
        TranslationOptions options = TranslationOptions.builder()
                .sourceLang("auto")
//                .targetLang("English")
                .targetLang(targetLanguage)
                .build();
        GenerationParam param = GenerationParam.builder()
                // 若没有配置环境变量，请用阿里云百炼API Key将下行替换为：.apiKey("sk-xxx")
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
//                .model("qwen-mt-plus")
                .model(model)
                .messages(Collections.singletonList(userMsg))
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .translationOptions(options)
                .build();
        try {
            GenerationResult call = gen.call(param);
            String content = call.getOutput().getChoices().get(0).getMessage().getContent();
            log.info("翻译完成，结果长度: {} ,内容是：{} ", content.length(),content);
            return content;
        } catch (NoApiKeyException e) {
            throw new RuntimeException(e);
        } catch (InputRequiredException e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 执行法律咨询的模拟方法
     */
    private Map<String, Object> performLegalConsultation(LegalRequest request) {
        Map<String, Object> response = new HashMap<>();
        
        // 根据咨询目的和类型生成更精准的回答
        Generation gen = new Generation();
        Message systemMsg = Message.builder()
                .role(Role.SYSTEM.getValue())
                .content("你是资深律师， 请根据用户咨询类型，核心诉求，咨询目的，详细描述 ，回答用户，用词要严谨 。")
                .build();
        Message userMsg = Message.builder()
                .role(Role.USER.getValue())
                .content("咨询吗目的： "+request.getConsultationPurpose()   +" , 核心诉求：" + request.getCoreDemand() +
                        " , 咨询类型：" + request.getConsultationType()+" , 详细描述 ： "+ request.getInputText())
                .build();
        GenerationParam param = GenerationParam.builder()
                // 若没有配置环境变量，请用百炼API Key将下行替换为：.apiKey("sk-xxx")
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
//                .model("farui-plus")
                .model(request.getModel())
                .messages(Arrays.asList(systemMsg, userMsg))
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .build();
        try {
            GenerationResult call = gen.call(param);
            response.put("answer", call.getOutput().getChoices().get(0).getMessage().getContent());
            log.info("法律咨询完成，结果长度: {} ,内容是：{} ", call);
        } catch (NoApiKeyException e) {
            throw new RuntimeException(e);
        } catch (InputRequiredException e) {
            throw new RuntimeException(e);
        }

        response.put("category", getCategoryByType(request.getConsultationType()));
        response.put("jurisdiction", "中国大陆");
        response.put("confidence", 0.85);
        response.put("relatedLaws", getRelatedLaws(request.getConsultationType()));
        response.put("suggestions", getSuggestions(request.getConsultationPurpose()));
        return response;
    }
    

    
    /**
     * 根据咨询类型获取分类
     */
    private String getCategoryByType(String consultationType) {
        switch (consultationType) {
            case "document_generation":
                return "文档生成咨询";
            case "contract_review":
                return "合同审查";
            case "legal_advice":
                return "法律建议";
            default:
                return "一般法律咨询";
        }
    }
    
    /**
     * 根据咨询类型获取相关法律条文
     */
    private String[] getRelatedLaws(String consultationType) {
        switch (consultationType) {
            case "document_generation":
                return new String[]{"民法典", "合同法", "个人信息保护法"};
            case "contract_review":
                return new String[]{"合同法", "民法典", "公司法"};
            case "legal_advice":
                return new String[]{"民法典", "劳动法", "消费者权益保护法"};
            default:
                return new String[]{"民法典", "合同法", "劳动法"};
        }
    }
    
    /**
     * 根据咨询目的获取建议
     */
    private String[] getSuggestions(String consultationPurpose) {
        return new String[]{
            "收集相关证据材料",
            "咨询专业律师",
            "了解相关法律条文",
            "保护个人隐私信息"
        };
    }

    /**
     * 执行意图分析的模拟方法
     */
    private Map<String, Object> performIntentAnalysis(IntentRequest request) {
        Map<String, Object> response = new HashMap<>();
        response.put("intent", "查询信息");
        response.put("confidence", 0.92);
        response.put("entities", new String[]{"时间", "地点", "人物"});
        response.put("sentiment", "中性");
        response.put("emotion", "平静");
        response.put("domain", request.getDomain() != null ? request.getDomain() : "通用");
        return response;
    }



    /**
     * 生成请求ID
     */
    private String generateRequestId() {
        return "REQ_" + System.currentTimeMillis() + "_" + (int)(Math.random() * 1000);
    }
}
