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

import com.unicorn.hgzero.ai.biz.domain.Term;
import com.unicorn.hgzero.ai.biz.usecase.TermDetectionUseCase;
import com.unicorn.hgzero.ai.infra.dto.request.TermDetectionRequest;
import com.unicorn.hgzero.ai.infra.dto.response.TermDetectionResponse;
import com.unicorn.hgzero.ai.infra.dto.common.DetectedTermDto;
import com.unicorn.hgzero.ai.infra.dto.common.HighlightInfoDto;
import com.unicorn.hgzero.ai.infra.dto.common.TextPositionDto;
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.List;
import java.util.stream.Collectors;

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

    private final TermDetectionUseCase termDetectionUseCase;

    @PostMapping("/detect")
    @Operation(summary = "전문용어 감지", description = "회의록 텍스트에서 전문용어를 자동으로 감지합니다")
    public ResponseEntity<ApiResponse<TermDetectionResponse>> detectTerms(
            @Valid @RequestBody TermDetectionRequest request) {

        log.info("전문용어 감지 요청 - meetingId: {}, organizationId: {}",
            request.getMeetingId(), request.getOrganizationId());

        List<Term> terms = termDetectionUseCase.detectTerms(
            request.getMeetingId(),
            request.getText(),
            request.getOrganizationId()
        );

        List<DetectedTermDto> detectedTerms = terms.stream()
                .map(t -> DetectedTermDto.builder()
                        .term(t.getTerm())
                        .position(t.getPosition() != null ? TextPositionDto.builder()
                                .line(t.getPosition().getLine())
                                .offset(t.getPosition().getOffset())
                                .build() : null)
                        .confidence(t.getConfidence())
                        .category(t.getCategory())
                        .highlight(t.getHighlight())
                        .build())
                .collect(Collectors.toList());

        List<HighlightInfoDto> highlightInfo = detectedTerms.stream()
                .filter(t -> Boolean.TRUE.equals(t.getHighlight()))
                .map(t -> HighlightInfoDto.builder()
                        .term(t.getTerm())
                        .position(t.getPosition())
                        .style("background-color: yellow")
                        .tooltip("용어 설명 로딩 중...")
                        .build())
                .collect(Collectors.toList());

        TermDetectionResponse response = TermDetectionResponse.builder()
                .detectedTerms(detectedTerms)
                .totalCount(detectedTerms.size())
                .highlightInfo(highlightInfo)
                .build();

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