package com.zioinfo.cms.ai;

import com.zioinfo.cms.common.ApiResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * GUARDiA CMS AI 도구 API (Ollama 온프레미스 + Java 폴백).
 *
 * <p>모든 엔드포인트는 Ollama 미가용 시에도 폴백으로 동작한다.
 */
@RestController
@RequestMapping("/api/cms/ai")
@RequiredArgsConstructor
public class AiController {

    private final AiService aiService;

    @GetMapping("/status")
    public ApiResponse<Map<String, Object>> status() {
        return ApiResponse.ok(Map.of("ollamaAvailable", aiService.ollamaAvailable()));
    }

    /** 1. 콘텐츠 초안 생성. */
    @PostMapping("/draft")
    public ApiResponse<Map<String, String>> draft(@RequestBody Map<String, String> req) {
        String text = aiService.draft(req.get("kind"), req.get("topic"), req.get("tone"));
        return ApiResponse.ok(Map.of("draft", text));
    }

    /** 2. 이미지 태깅/대체텍스트 (base64 이미지). */
    @PostMapping("/image-tags")
    public ApiResponse<Map<String, Object>> imageTags(@RequestBody Map<String, String> req) {
        return ApiResponse.ok(aiService.imageTags(req.get("imageBase64"), req.get("fileName")));
    }

    /** 3. SEO 제안. */
    @PostMapping("/seo")
    public ApiResponse<Map<String, Object>> seo(@RequestBody Map<String, String> req) {
        return ApiResponse.ok(aiService.seoSuggest(req.get("title"), req.get("body")));
    }

    /** 4. 번역. */
    @PostMapping("/translate")
    public ApiResponse<Map<String, String>> translate(@RequestBody Map<String, String> req) {
        String out = aiService.translate(req.get("text"), req.getOrDefault("targetLocale", "en"));
        return ApiResponse.ok(Map.of("translated", out));
    }

    /** 6. 리뷰 요약·감성. */
    @PostMapping("/review-summary")
    public ApiResponse<Map<String, Object>> reviewSummary(@RequestBody Map<String, Object> req) {
        @SuppressWarnings("unchecked")
        List<String> reviews = (List<String>) req.getOrDefault("reviews", List.of());
        return ApiResponse.ok(aiService.reviewSummary(reviews));
    }

    /** 7. 자연어 검색 키워드. */
    @PostMapping("/search-keywords")
    public ApiResponse<Map<String, Object>> searchKeywords(@RequestBody Map<String, String> req) {
        return ApiResponse.ok(Map.of("keywords", aiService.searchKeywords(req.get("query"))));
    }

    /** 8. UGC 모더레이션. */
    @PostMapping("/moderate")
    public ApiResponse<Map<String, Object>> moderate(@RequestBody Map<String, String> req) {
        return ApiResponse.ok(aiService.moderate(req.get("text")));
    }
}
