package com.unicorn.hgzero.ai.infra.controller;

import com.unicorn.hgzero.ai.biz.domain.ProcessedTranscript;
import com.unicorn.hgzero.ai.biz.usecase.TranscriptProcessUseCase;
import com.unicorn.hgzero.ai.infra.dto.request.TranscriptProcessRequest;
import com.unicorn.hgzero.ai.infra.dto.response.TranscriptProcessResponse;
import com.unicorn.hgzero.ai.infra.dto.common.*;
import com.unicorn.hgzero.common.dto.ApiResponse;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.stream.Collectors;

/**
 * 회의록 자동 작성 Controller
 * POST /api/transcripts/process
 */
@RestController
@RequestMapping("/api/ai/transcripts")
@RequiredArgsConstructor
@Slf4j
@Tag(name = "Transcript", description = "회의록 자동 작성 API")
public class TranscriptController {

    private final TranscriptProcessUseCase transcriptProcessUseCase;

    @PostMapping("/process")
    @Operation(summary = "회의록 자동 작성", description = "STT에서 변환된 텍스트를 받아 LLM 기반으로 회의록을 자동 작성합니다")
    public ResponseEntity<ApiResponse<TranscriptProcessResponse>> processTranscript(
            @RequestHeader("X-User-Id") String userId,
            @RequestHeader("X-User-Name") String userName,
            @Valid @RequestBody TranscriptProcessRequest request) {

        log.info("회의록 자동 작성 요청 - meetingId: {}, userId: {}", request.getMeetingId(), userId);

        ProcessedTranscript result = transcriptProcessUseCase.processTranscript(
            request.getMeetingId(),
            request.getTranscriptText(),
            request.getUserId() != null ? request.getUserId() : userId,
            request.getUserName() != null ? request.getUserName() : userName,
            request.getContext() != null ? request.getContext().getTitle() : "",
            request.getContext() != null ? request.getContext().getParticipants() : null,
            request.getContext() != null ? request.getContext().getAgenda() : null
        );

        TranscriptProcessResponse response = mapToResponse(result);
        return ResponseEntity.ok(ApiResponse.success(response));
    }

    private TranscriptProcessResponse mapToResponse(ProcessedTranscript domain) {
        return TranscriptProcessResponse.builder()
                .transcriptId(domain.getTranscriptId())
                .meetingId(domain.getMeetingId())
                .content(mapContent(domain))
                .suggestions(null) // TODO: 실시간 제안 기능 구현 시 추가
                .createdAt(domain.getCreatedAt())
                .status(domain.getStatus())
                .build();
    }

    private TranscriptContentDto mapContent(ProcessedTranscript domain) {
        return TranscriptContentDto.builder()
                .summary(domain.getSummary())
                .discussions(domain.getDiscussions().stream()
                        .map(d -> DiscussionItemDto.builder()
                                .topic(d.getTopic())
                                .speaker(d.getSpeaker())
                                .content(d.getContent())
                                .build())
                        .collect(Collectors.toList()))
                .decisions(domain.getDecisions().stream()
                        .map(d -> DecisionItemDto.builder()
                                .content(d.getContent())
                                .decisionMaker(d.getDecisionMaker())
                                .category(d.getCategory())
                                .build())
                        .collect(Collectors.toList()))
                .pendingItems(domain.getPendingItems())
                .build();
    }
}
