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

import com.unicorn.hgzero.ai.biz.usecase.TermExplanationUseCase;
import com.unicorn.hgzero.ai.infra.dto.response.TermExplanationResponse;
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 lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.stream.Collectors;

/**
 * 전문용어 설명 Controller
 * GET /api/terms/{term}/explain
 */
@RestController
@RequestMapping("/api/ai/terms")
@RequiredArgsConstructor
@Slf4j
@Tag(name = "Term", description = "전문용어 감지 및 설명 API")
public class ExplanationController {

    private final TermExplanationUseCase termExplanationUseCase;

    @GetMapping("/{term}/explain")
    @Operation(summary = "맥락 기반 용어 설명", description = "전문용어에 대한 맥락 기반 설명을 생성합니다")
    public ResponseEntity<ApiResponse<TermExplanationResponse>> explainTerm(
            @PathVariable String term,
            @RequestParam String meetingId,
            @RequestParam(required = false) String context) {

        log.info("용어 설명 요청 - term: {}, meetingId: {}", term, meetingId);

        TermExplanationUseCase.TermExplanationResult result = termExplanationUseCase.explainTerm(
            term,
            meetingId,
            context
        );

        TermExplanationResponse response = TermExplanationResponse.builder()
                .term(result.term())
                .basicDefinition(result.basicDefinition())
                .contextualMeaning(result.contextualMeaning())
                .useCases(result.useCases())
                .relatedProjects(result.relatedProjects().stream()
                        .map(p -> RelatedProjectDto.builder()
                                .name(p.name())
                                .relevance(p.relevance())
                                .build())
                        .collect(Collectors.toList()))
                .pastDiscussions(result.pastDiscussions().stream()
                        .map(d -> PastDiscussionDto.builder()
                                .date(d.date())
                                .participants(d.participants())
                                .summary(d.summary())
                                .link(d.link())
                                .build())
                        .collect(Collectors.toList()))
                .references(result.references().stream()
                        .map(r -> ReferenceDto.builder()
                                .title(r.title())
                                .type(r.type())
                                .link(r.link())
                                .build())
                        .collect(Collectors.toList()))
                .build();

        return ResponseEntity.ok(ApiResponse.success(response));
    }
}
