package com.cy.guoyan.admin.module.ai.service.chatsession;

import com.cy.guoyan.admin.framework.security.core.util.SecurityFrameworkUtils;
import com.cy.guoyan.admin.module.ai.controller.admin.chatsession.vo.ChatSessionPageReqVO;
import com.cy.guoyan.admin.module.ai.controller.admin.chatsession.vo.ChatSessionSaveReqVO;
import com.cy.guoyan.admin.module.ai.dal.dataobject.chatapp.ChatAppDO;
import com.cy.guoyan.admin.module.ai.dal.mysql.chatapp.ChatAppMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import com.cy.guoyan.admin.module.ai.dal.dataobject.chatsession.ChatSessionDO;
import com.cy.guoyan.admin.framework.common.pojo.PageResult;
import com.cy.guoyan.admin.framework.common.util.object.BeanUtils;
import com.cy.guoyan.admin.module.ai.dal.mysql.chatsession.ChatSessionMapper;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;
import static com.cy.guoyan.admin.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.cy.guoyan.admin.module.system.enums.ErrorCodeConstants.*;

/**
 * AI聊天会话 Service 实现类
 *
 * @author 管理员
 */
@Slf4j
@Service
@Validated
public class ChatSessionServiceImpl implements ChatSessionService {

    @Resource
    private ChatSessionMapper chatSessionMapper;

    @Resource
    private ChatAppMapper chatAppMapper;

    @Value("${dify.baseUrl}")
    private String difyBaseUrl;

//    @Value("${dify.chatKey}")
//    private String difyApiKey;

    private HttpURLConnection prepare(String method, String path,  String difyApiKey) throws IOException {
        URL url = new URL(difyBaseUrl + path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod(method);
//        String difyApiKey = getAppKey(appType);

        conn.setRequestProperty("Authorization", "Bearer " + difyApiKey);

        // 不建议在这里全局加 Content-Type，因为 DELETE 有时无 body
        return conn;
    }




    /** 读取响应 body 或抛异常 */
    private String readResponse(HttpURLConnection conn) throws IOException {
        int code = conn.getResponseCode();
        InputStream is = (code >= 200 && code < 300) ? conn.getInputStream() : conn.getErrorStream();
        if (is == null) throw new IOException("无返回流，HTTP " + code);
        String body;
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) {
            body = reader.lines().collect(Collectors.joining());
        }
        if (code < 200 || code >= 300) {
            throw new IOException("Dify 错误 HTTP " + code + "，" + body);
        }
        return body;
    }


    @Override
    public Long createChatSession(ChatSessionSaveReqVO createReqVO) {
        // 插入
        ChatSessionDO chatSession = BeanUtils.toBean(createReqVO, ChatSessionDO.class);
        chatSessionMapper.insert(chatSession);
        // 返回
        return chatSession.getId();
    }

    @Override
    public void updateChatSession(ChatSessionSaveReqVO updateReqVO) {
        // 校验存在
        validateChatSessionExists(updateReqVO.getId());
        // 更新
        ChatSessionDO updateObj = BeanUtils.toBean(updateReqVO, ChatSessionDO.class);
        chatSessionMapper.updateById(updateObj);
    }

    @Override
    public void deleteChatSession(Long id) throws IOException {
        ChatSessionDO chatSessionDO = chatSessionMapper.selectById(id);
        if (chatSessionDO == null) {
            throw exception(CHAT_SESSION_NOT_EXISTS);
        }

        ChatAppDO appDO = chatAppMapper.selectById(chatSessionDO.getAppId());
        if (appDO == null) {
            throw exception(CHAT_APP_NOT_EXISTS);
        }

        log.info("删除会话：{}", chatSessionDO.getDifyConversationId());
        HttpURLConnection conn = prepare("DELETE", "/v1/conversations/" + chatSessionDO.getDifyConversationId(), appDO.getAppKey());
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-Type", "application/json");
        String nickname = String.valueOf(SecurityFrameworkUtils.getLoginUser().getInfo().get("nickname"));

        // 写入 JSON 请求体：{ "user": "xxx" }
        String json = String.format("{\"user\": \"%s\"}", nickname);
        try (OutputStream os = conn.getOutputStream()) {
            byte[] input = json.getBytes(StandardCharsets.UTF_8);
            os.write(input, 0, input.length);
        }

        int responseCode = conn.getResponseCode();
        if (responseCode >= 200 && responseCode < 300) {
           log.info("会话删除成功");
        } else {
            try (BufferedReader br = new BufferedReader(new InputStreamReader(conn.getErrorStream(), StandardCharsets.UTF_8))) {
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    response.append(line);
                }
                throw new IOException("Dify 错误 HTTP " + responseCode + "，" + response.toString());
            }
        }
        // 删除
        chatSessionMapper.deleteById(id);
    }

    private void validateChatSessionExists(Long id) {
        if (chatSessionMapper.selectById(id) == null) {
            throw exception(CHAT_SESSION_NOT_EXISTS);
        }
    }

    @Override
    public ChatSessionDO getChatSession(Long id) {
        return chatSessionMapper.selectById(id);
    }

    @Override
    public PageResult<ChatSessionDO> getChatSessionPage(ChatSessionPageReqVO pageReqVO) {
        return chatSessionMapper.selectPage(pageReqVO);
    }

}