package com.gxwebsoft.house.controller;

import com.gxwebsoft.common.core.utils.JSONUtil;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.core.websocket.WebSocketServer;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.house.entity.HouseAiChatRequest;
import com.gxwebsoft.house.entity.HouseAiChatResponse;
import com.gxwebsoft.house.service.HouseAiChatService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;

/**
 * AI找房聊天控制器
 */
@Tag(name = "AI找房问答")
@RestController
@RequestMapping("/api/house/ai-chat")
public class HouseAiChatController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(HouseAiChatController.class);

    @Resource
    private HouseAiChatService houseAiChatService;
    @Resource
    private WebSocketServer webSocketServer;

    @Operation(summary = "发送AI找房问题")
    @PostMapping("/message")
    public ApiResult<?> message(@RequestBody HouseAiChatRequest request) {
        User loginUser = getLoginUser();
        if (loginUser == null) {
            return fail("请先登录后再使用AI找房");
        }
        if (loginUser.getTenantId() == null) {
            return fail("当前登录账号缺少租户信息，暂无法使用AI找房");
        }
        if (request.getQuestion() == null || request.getQuestion().trim().isEmpty()) {
            return fail("提问内容不能为空");
        }
        request.setUserId(loginUser.getUserId());
        request.setTenantId(loginUser.getTenantId());
        sendProgress(request);
        HouseAiChatResponse response;
        try {
            response = houseAiChatService.answer(request);
        } catch (Exception e) {
            log.error("AI找房处理失败，用户ID={}，会话ID={}", request.getUserId(), request.getConversationId(), e);
            return fail("AI服务暂时不可用，请稍后再试。");
        }
        if (sendResponse(request, response)) {
            return success("处理成功");
        }
        return success("处理成功", response);
    }

    private void sendProgress(HouseAiChatRequest request) {
        try {
            boolean delivered = webSocketServer.sendMessage(String.valueOf(request.getUserId()),
                "{\"type\":\"house_ai_progress\",\"message\":\"正在分析您的找房需求\"}");
            if (!delivered) {
                log.warn("AI找房进度未通过WebSocket送达，用户ID={}，会话ID={}",
                    request.getUserId(), request.getConversationId());
            }
        } catch (Exception e) {
            log.warn("AI找房进度WebSocket推送失败，用户ID={}，会话ID={}，原因={}",
                request.getUserId(), request.getConversationId(), e.toString());
        }
    }

    private boolean sendResponse(HouseAiChatRequest request, HouseAiChatResponse response) {
        try {
            boolean delivered = webSocketServer.sendMessage(String.valueOf(request.getUserId()),
                JSONUtil.toJSONString(response));
            if (!delivered) {
                log.warn("AI找房结果未通过WebSocket送达，用户ID={}，会话ID={}",
                    request.getUserId(), request.getConversationId());
            }
            return delivered;
        } catch (Exception e) {
            log.warn("AI找房结果WebSocket推送失败，用户ID={}，会话ID={}，原因={}",
                request.getUserId(), request.getConversationId(), e.toString());
            return false;
        }
    }

    @Operation(summary = "清空AI找房会话")
    @PostMapping("/session/clear")
    public ApiResult<?> clearSession(@RequestBody HouseAiChatRequest request) {
        User loginUser = getLoginUser();
        if (loginUser == null) {
            return fail("请先登录后再使用AI找房");
        }
        if (loginUser.getTenantId() == null) {
            return fail("当前登录账号缺少租户信息，暂无法使用AI找房");
        }
        request.setUserId(loginUser.getUserId());
        request.setTenantId(loginUser.getTenantId());
        houseAiChatService.clearSession(request);
        return success();
    }
}
