package com.infoepoch.pms.agent.platform.chat.adapter.in.web;

import com.infoepoch.pms.agent.platform.chat.application.ChatService;
import com.infoepoch.pms.agent.platform.chat.application.dto.*;
import com.infoepoch.pms.agent.platform.shared.response.Result;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import java.util.List;

/**
 * 用户对话接口控制器。
 * <p>
 * 提供会话管理和消息收发的 REST API。
 * </p>
 */
@RestController
@RequestMapping("/api/chat")
@RequiredArgsConstructor
public class ChatController {

    private final ChatService chatService;

    /**
     * 创建新会话。
     * <p>
     * POST /api/chat/sessions
     */
    @PostMapping("/sessions")
    public Result<SessionResponse> createSession(@Valid @RequestBody CreateSessionRequest req) {
        return Result.success(chatService.createSession(req));
    }

    /**
     * 查询用户会话列表。
     * <p>
     * GET /api/chat/sessions?userId={userId}
     */
    @GetMapping("/sessions")
    public Result<List<SessionResponse>> listSessions(@RequestParam String userId) {
        return Result.success(chatService.listSessions(userId));
    }

    /**
     * 获取会话信息。
     * <p>
     * GET /api/chat/sessions/{sessionId}
     */
    @GetMapping("/sessions/{sessionId}")
    public Result<SessionResponse> getSession(@PathVariable String sessionId) {
        return Result.success(chatService.getSession(sessionId));
    }

    /**
     * 删除指定会话。
     * <p>
     * DELETE /api/chat/sessions/{sessionId}
     */
    @DeleteMapping("/sessions/{sessionId}")
    public Result<Void> deleteSession(@PathVariable String sessionId) {
        chatService.deleteSession(sessionId);
        return Result.success(null);
    }

    /**
     * 标记清除上下文待生效。
     */
    @PostMapping("/sessions/{sessionId}/context-reset")
    public Result<SessionResponse> markContextResetPending(@PathVariable String sessionId) {
        return Result.success(chatService.markContextResetPending(sessionId));
    }

    /**
     * 撤销清除上下文待生效。
     */
    @DeleteMapping("/sessions/{sessionId}/context-reset")
    public Result<SessionResponse> clearContextResetPending(@PathVariable String sessionId) {
        return Result.success(chatService.clearContextResetPending(sessionId));
    }

    /**
     * 发送用户消息，获取 AI 回复。
     * <p>
     * POST /api/chat/sessions/{sessionId}/message
     */
    @PostMapping("/sessions/{sessionId}/message")
    public Result<MessageResponse> sendMessage(
            @PathVariable String sessionId,
            @Valid @RequestBody SendMessageRequest req) {
        return Result.success(chatService.sendMessage(sessionId, req));
    }

    /**
     * 发送用户消息，并以 SSE 方式流式返回 AI 输出。
     * <p>
     * POST /api/chat/sessions/{sessionId}/message/stream
     */
    @PostMapping(value = "/sessions/{sessionId}/message/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<ServerSentEvent<ChatStreamEventResponse>> streamMessage(
            @PathVariable String sessionId,
            @Valid @RequestBody SendMessageRequest req) {
        return Flux.defer(() -> chatService.streamMessage(sessionId, req))
                .map(event -> ServerSentEvent.<ChatStreamEventResponse>builder()
                        .event(event.getType())
                        .data(event)
                        .build())
                .onErrorResume(error -> Flux.just(ServerSentEvent.<ChatStreamEventResponse>builder()
                        .event("error")
                        .data(new ChatStreamEventResponse("error", error.getMessage(), null, null))
                        .build()));
    }

    /**
     * 查询当前会话的待审批事项。
     * <p>
     * GET /api/chat/sessions/{sessionId}/approval/pending
     */
    @GetMapping("/sessions/{sessionId}/approval/pending")
    public Result<PendingApprovalResponse> getPendingApproval(@PathVariable String sessionId) {
        return Result.success(chatService.getPendingApproval(sessionId));
    }

    /**
     * 提交审批决策，并以 SSE 方式流式返回恢复执行过程。
     * <p>
     * POST /api/chat/sessions/{sessionId}/approval/decision/stream
     */
    @PostMapping(value = "/sessions/{sessionId}/approval/decision/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<ServerSentEvent<ChatStreamEventResponse>> streamApprovalDecision(
            @PathVariable String sessionId,
            @Valid @RequestBody ApprovalDecisionRequest req) {
        return Flux.defer(() -> chatService.streamApprovalDecision(sessionId, req))
                .map(event -> ServerSentEvent.<ChatStreamEventResponse>builder()
                        .event(event.getType())
                        .data(event)
                        .build())
                .onErrorResume(error -> Flux.just(ServerSentEvent.<ChatStreamEventResponse>builder()
                        .event("error")
                        .data(new ChatStreamEventResponse("error", error.getMessage(), null, null))
                        .build()));
    }

    /**
     * 获取会话的完整对话历史。
     * <p>
     * GET /api/chat/sessions/{sessionId}/messages
     */
    @GetMapping("/sessions/{sessionId}/messages")
    public Result<List<ConversationResponse>> getMessages(@PathVariable String sessionId) {
        return Result.success(chatService.getMessages(sessionId));
    }
}
