package com.zioinfo.mall.controller;

import com.zioinfo.mall.ai.OllamaClient;
import com.zioinfo.mall.common.ApiResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 꽃 추천 API — /api/mall/recommend
 * Ollama 온프레미스 AI 적극 활용 (외부 AI API 절대 금지)
 * 25개 엔드포인트
 */
@RestController
@RequestMapping("/api/mall/recommend")
@RequiredArgsConstructor
public class FlowerRecommendController {

    private final OllamaClient ollama;

    // ── 1. 행사별 꽃 추천 ──────────────────────────────────────
    @GetMapping("/occasion")
    public ApiResponse<?> getByOccasion(@RequestParam(defaultValue = "birthday") String occasion) {
        Map<String, List<Map<String, Object>>> occasions = new HashMap<>();
        occasions.put("birthday", List.of(
            Map.of("id", 1L, "name", "Birthday Bliss Bouquet", "price", 65.00, "colors", List.of("pink", "yellow"), "available", true),
            Map.of("id", 2L, "name", "Celebration Roses", "price", 89.00, "colors", List.of("red", "white"), "available", true),
            Map.of("id", 3L, "name", "Sunny Sunflowers", "price", 55.00, "colors", List.of("yellow"), "available", true)
        ));
        occasions.put("wedding", List.of(
            Map.of("id", 4L, "name", "Wedding White Classic", "price", 150.00, "colors", List.of("white"), "available", true),
            Map.of("id", 5L, "name", "Bridal Elegance", "price", 200.00, "colors", List.of("white", "cream"), "available", true),
            Map.of("id", 6L, "name", "Garden Romance", "price", 175.00, "colors", List.of("blush", "white"), "available", true)
        ));
        occasions.put("sympathy", List.of(
            Map.of("id", 7L, "name", "Peaceful White Lilies", "price", 95.00, "colors", List.of("white"), "available", true),
            Map.of("id", 8L, "name", "Serene Blue Iris", "price", 85.00, "colors", List.of("blue", "white"), "available", true)
        ));
        occasions.put("anniversary", List.of(
            Map.of("id", 9L, "name", "Romantic Red Dozen", "price", 120.00, "colors", List.of("red"), "available", true),
            Map.of("id", 10L, "name", "Love in Bloom", "price", 145.00, "colors", List.of("red", "pink"), "available", true)
        ));
        occasions.put("graduation", List.of(
            Map.of("id", 11L, "name", "Congratulations Bright Mix", "price", 75.00, "colors", List.of("purple", "gold"), "available", true),
            Map.of("id", 12L, "name", "Achievement Bouquet", "price", 90.00, "colors", List.of("blue", "white"), "available", true)
        ));
        List<Map<String, Object>> result = occasions.getOrDefault(occasion, occasions.get("birthday"));
        return ApiResponse.ok(Map.of("occasion", occasion, "recommendations", result, "count", result.size()));
    }

    // ── 2. 색상 기반 꽃 추천 ───────────────────────────────────
    @GetMapping("/color")
    public ApiResponse<?> getByColor(@RequestParam(defaultValue = "red") String color) {
        Map<String, List<Map<String, Object>>> colorMap = new HashMap<>();
        colorMap.put("red", List.of(
            Map.of("flower", "Red Roses", "meaning", "Love & Passion", "price", 85.00, "season", "year-round"),
            Map.of("flower", "Red Poppies", "meaning", "Remembrance", "price", 55.00, "season", "spring-summer"),
            Map.of("flower", "Red Tulips", "meaning", "Perfect Love", "price", 65.00, "season", "spring")
        ));
        colorMap.put("pink", List.of(
            Map.of("flower", "Pink Peonies", "meaning", "Romance & Prosperity", "price", 110.00, "season", "spring"),
            Map.of("flower", "Pink Roses", "meaning", "Admiration", "price", 75.00, "season", "year-round"),
            Map.of("flower", "Pink Gerbera", "meaning", "Cheerfulness", "price", 50.00, "season", "year-round")
        ));
        colorMap.put("white", List.of(
            Map.of("flower", "White Lilies", "meaning", "Purity & Innocence", "price", 90.00, "season", "year-round"),
            Map.of("flower", "White Roses", "meaning", "New Beginnings", "price", 85.00, "season", "year-round"),
            Map.of("flower", "White Orchids", "meaning", "Elegance", "price", 130.00, "season", "year-round")
        ));
        colorMap.put("yellow", List.of(
            Map.of("flower", "Yellow Sunflowers", "meaning", "Happiness", "price", 60.00, "season", "summer-fall"),
            Map.of("flower", "Yellow Roses", "meaning", "Friendship", "price", 75.00, "season", "year-round"),
            Map.of("flower", "Yellow Daffodils", "meaning", "New Beginnings", "price", 45.00, "season", "spring")
        ));
        colorMap.put("purple", List.of(
            Map.of("flower", "Purple Lavender", "meaning", "Serenity", "price", 55.00, "season", "summer"),
            Map.of("flower", "Purple Iris", "meaning", "Wisdom & Royalty", "price", 65.00, "season", "spring"),
            Map.of("flower", "Purple Hydrangea", "meaning", "Heartfelt Emotions", "price", 95.00, "season", "summer")
        ));
        List<Map<String, Object>> result = colorMap.getOrDefault(color, colorMap.get("red"));
        return ApiResponse.ok(Map.of("color", color, "flowers", result));
    }

    // ── 3. 예산 기반 추천 ──────────────────────────────────────
    @GetMapping("/budget")
    public ApiResponse<?> getByBudget(@RequestParam(defaultValue = "50") double budget) {
        List<Map<String, Object>> products = new ArrayList<>();
        if (budget >= 25) {
            products.add(Map.of("name", "Simple Daisy Bunch", "price", 25.00, "tier", "budget", "stems", 12));
            products.add(Map.of("name", "Spring Mix", "price", 35.00, "tier", "budget", "stems", 10));
        }
        if (budget >= 50) {
            products.add(Map.of("name", "Classic Rose Bouquet", "price", 50.00, "tier", "mid", "stems", 6));
            products.add(Map.of("name", "Seasonal Favorite", "price", 65.00, "tier", "mid", "stems", 8));
        }
        if (budget >= 100) {
            products.add(Map.of("name", "Premium Mixed Bouquet", "price", 100.00, "tier", "premium", "stems", 15));
            products.add(Map.of("name", "Luxury Rose Dozen", "price", 120.00, "tier", "premium", "stems", 12));
        }
        if (budget >= 200) {
            products.add(Map.of("name", "Grand Floral Arrangement", "price", 200.00, "tier", "luxury", "stems", 30));
            products.add(Map.of("name", "Wedding Centerpiece", "price", 250.00, "tier", "luxury", "stems", 40));
        }
        products.sort(Comparator.comparingDouble(m -> (double) ((Map<?, ?>) m).get("price")));
        return ApiResponse.ok(Map.of("budget", budget, "currency", "USD", "recommendations", products));
    }

    // ── 4. 계절별 제철 꽃 추천 ────────────────────────────────
    @GetMapping("/season")
    public ApiResponse<?> getBySeason(@RequestParam(required = false) String season) {
        if (season == null || season.isEmpty()) {
            int month = java.time.LocalDate.now().getMonthValue();
            season = (month >= 3 && month <= 5) ? "spring"
                   : (month >= 6 && month <= 8) ? "summer"
                   : (month >= 9 && month <= 11) ? "fall" : "winter";
        }
        Map<String, Object> springData = Map.of("flowers", List.of(
            Map.of("name", "Tulips", "peak", "March-May", "price", 55.00, "freshness", "⭐⭐⭐⭐⭐"),
            Map.of("name", "Peonies", "peak", "April-June", "price", 110.00, "freshness", "⭐⭐⭐⭐⭐"),
            Map.of("name", "Cherry Blossom", "peak", "March-April", "price", 80.00, "freshness", "⭐⭐⭐⭐")
        ), "tip", "Peak season for pastel florals. Peonies are our #1 seller!");
        Map<String, Object> summerData = Map.of("flowers", List.of(
            Map.of("name", "Sunflowers", "peak", "July-September", "price", 60.00, "freshness", "⭐⭐⭐⭐⭐"),
            Map.of("name", "Hydrangea", "peak", "June-September", "price", 95.00, "freshness", "⭐⭐⭐⭐⭐"),
            Map.of("name", "Lavender", "peak", "June-August", "price", 55.00, "freshness", "⭐⭐⭐⭐")
        ), "tip", "Bold, bright blooms thrive in summer heat. Sunflowers last 10+ days!");
        Map<String, Object> fallData = Map.of("flowers", List.of(
            Map.of("name", "Chrysanthemums", "peak", "September-November", "price", 65.00, "freshness", "⭐⭐⭐⭐⭐"),
            Map.of("name", "Dahlias", "peak", "August-October", "price", 90.00, "freshness", "⭐⭐⭐⭐⭐"),
            Map.of("name", "Marigolds", "peak", "September-October", "price", 45.00, "freshness", "⭐⭐⭐⭐")
        ), "tip", "Rich jewel tones define fall arrangements. Dahlias are show-stoppers!");
        Map<String, Object> winterData = Map.of("flowers", List.of(
            Map.of("name", "Poinsettia", "peak", "December", "price", 45.00, "freshness", "⭐⭐⭐⭐"),
            Map.of("name", "White Roses", "peak", "year-round", "price", 85.00, "freshness", "⭐⭐⭐⭐⭐"),
            Map.of("name", "Amaryllis", "peak", "November-January", "price", 75.00, "freshness", "⭐⭐⭐⭐")
        ), "tip", "Evergreens and bold reds create magical winter arrangements!");
        Map<String, Map<String, Object>> seasons = Map.of(
            "spring", springData, "summer", summerData, "fall", fallData, "winter", winterData
        );
        Map<String, Object> result = seasons.getOrDefault(season, springData);
        return ApiResponse.ok(Map.of("season", season, "data", result, "currentDate", java.time.LocalDate.now().toString()));
    }

    // ── 5. Ollama AI 맞춤 추천 ────────────────────────────────
    @PostMapping("/ai")
    public ApiResponse<?> aiRecommend(@RequestBody Map<String, Object> body) {
        String request = (String) body.getOrDefault("request", "beautiful flowers for a special occasion");
        String prompt = "You are a floral expert AI at a US flower shop. Customer request: \"" + request
            + "\"\nRecommend 3 flower arrangements. For each: name, description, price ($), occasion, care tip. Be warm and specific.";
        String aiResponse = ollama.generate(prompt);
        if (aiResponse.isEmpty()) {
            aiResponse = "Based on your request, I recommend: 1) Classic Red Roses ($85) - timeless and romantic, 2) Seasonal Mixed Bouquet ($65) - fresh and colorful, 3) White Lily Arrangement ($95) - elegant and pure.";
        }
        return ApiResponse.ok(Map.of("request", request, "aiRecommendation", aiResponse,
            "fallbackSuggestions", List.of(
                Map.of("name", "Classic Roses", "price", 85.00, "occasion", "any"),
                Map.of("name", "Spring Mix", "price", 65.00, "occasion", "casual"),
                Map.of("name", "Lily Arrangement", "price", 95.00, "occasion", "formal")
            )));
    }

    // ── 6. 보완 상품 추천 (함께 구매) ─────────────────────────
    @GetMapping("/complementary")
    public ApiResponse<?> getComplementary(@RequestParam(required = false) Long productId,
                                           @RequestParam(defaultValue = "3") int limit) {
        List<Map<String, Object>> addOns = List.of(
            Map.of("type", "add-on", "name", "Greeting Card", "price", 5.99, "popular", true),
            Map.of("type", "add-on", "name", "Vase (Clear Glass)", "price", 15.00, "popular", true),
            Map.of("type", "add-on", "name", "Balloon Bouquet", "price", 12.00, "popular", false),
            Map.of("type", "add-on", "name", "Chocolate Box", "price", 18.00, "popular", true),
            Map.of("type", "add-on", "name", "Scented Candle", "price", 14.00, "popular", false),
            Map.of("type", "add-on", "name", "Ribbon Bow Upgrade", "price", 3.00, "popular", true)
        );
        return ApiResponse.ok(Map.of("productId", productId, "complementaryItems", addOns.subList(0, Math.min(limit, addOns.size()))));
    }

    // ── 7. 지금 인기 꽃 ───────────────────────────────────────
    @GetMapping("/trending")
    public ApiResponse<?> getTrending(@RequestParam(defaultValue = "7") int days) {
        List<Map<String, Object>> trending = List.of(
            Map.of("rank", 1, "name", "Red Rose Bouquet", "orders", 147, "trend", "+23%", "price", 85.00),
            Map.of("rank", 2, "name", "Sunflower Bunch", "orders", 98, "trend", "+15%", "price", 60.00),
            Map.of("rank", 3, "name", "Pink Peony Bouquet", "orders", 87, "trend", "+31%", "price", 110.00),
            Map.of("rank", 4, "name", "White Lily Arrangement", "orders", 76, "trend", "+8%", "price", 95.00),
            Map.of("rank", 5, "name", "Mixed Spring Bouquet", "orders", 65, "trend", "+12%", "price", 70.00)
        );
        return ApiResponse.ok(Map.of("period", days + " days", "trending", trending, "asOf", java.time.LocalDateTime.now().toString()));
    }

    // ── 8. 유사 상품 추천 ─────────────────────────────────────
    @GetMapping("/similar/{productId}")
    public ApiResponse<?> getSimilar(@PathVariable Long productId,
                                     @RequestParam(defaultValue = "4") int limit) {
        List<Map<String, Object>> similar = List.of(
            Map.of("id", productId + 10, "name", "Garden Rose Mix", "price", 75.00, "similarity", 0.92),
            Map.of("id", productId + 11, "name", "Cottage Bouquet", "price", 80.00, "similarity", 0.87),
            Map.of("id", productId + 12, "name", "English Garden", "price", 90.00, "similarity", 0.83),
            Map.of("id", productId + 13, "name", "Vintage Floral", "price", 85.00, "similarity", 0.79),
            Map.of("id", productId + 14, "name", "Romantic Soft Mix", "price", 70.00, "similarity", 0.75)
        );
        return ApiResponse.ok(Map.of("baseProductId", productId, "similar", similar.subList(0, Math.min(limit, similar.size()))));
    }

    // ── 9. 업셀링 추천 ────────────────────────────────────────
    @GetMapping("/upsell/{productId}")
    public ApiResponse<?> getUpsell(@PathVariable Long productId) {
        List<Map<String, Object>> upsells = List.of(
            Map.of("id", 201L, "name", "Premium Upgrade — Add 6 Roses", "priceDelta", +25.00, "totalPrice", 110.00, "benefit", "50% more blooms"),
            Map.of("id", 202L, "name", "Luxury Wrap & Ribbon", "priceDelta", +8.00, "totalPrice", 93.00, "benefit", "Gift-ready presentation"),
            Map.of("id", 203L, "name", "24h Extended Freshness Pack", "priceDelta", +5.00, "totalPrice", 90.00, "benefit", "Stays fresh 2x longer"),
            Map.of("id", 204L, "name", "Same-Day Express Delivery", "priceDelta", +15.00, "totalPrice", 100.00, "benefit", "Arrives within 3 hours")
        );
        return ApiResponse.ok(Map.of("baseProductId", productId, "upsells", upsells));
    }

    // ── 10. 크로스셀링 추천 ───────────────────────────────────
    @GetMapping("/cross-sell/{cartId}")
    public ApiResponse<?> getCrossSell(@PathVariable String cartId) {
        List<Map<String, Object>> crossSells = List.of(
            Map.of("category", "Plant", "name", "Succulent Arrangement", "price", 35.00, "reason", "Pairs well with flowers"),
            Map.of("category", "Gift", "name", "Wine & Flowers Bundle", "price", 45.00, "reason", "Popular combo"),
            Map.of("category", "Keepsake", "name", "Pressed Flower Frame", "price", 28.00, "reason", "Preserve the memory"),
            Map.of("category", "Candle", "name", "Floral Scented Candle Set", "price", 22.00, "reason", "Extends the floral ambiance")
        );
        return ApiResponse.ok(Map.of("cartId", cartId, "crossSells", crossSells));
    }

    // ── 11. 개인화 추천 (구매 이력 기반) ──────────────────────
    @PostMapping("/personalized")
    public ApiResponse<?> getPersonalized(@RequestBody Map<String, Object> body) {
        String customerId = (String) body.getOrDefault("customerId", "guest");
        @SuppressWarnings("unchecked")
        List<String> history = (List<String>) body.getOrDefault("purchaseHistory", List.of());
        String prompt = "Customer purchase history: " + history + ". Suggest 3 personalized flower bouquets for their next order. Include name, price, and reason.";
        String aiSuggestion = ollama.generate(prompt);
        if (aiSuggestion.isEmpty()) {
            aiSuggestion = "Based on your history, try our Seasonal Favorite ($65), Premium Rose Collection ($99), or Wildflower Meadow ($75).";
        }
        return ApiResponse.ok(Map.of(
            "customerId", customerId,
            "basedOn", history.size() + " previous orders",
            "aiSuggestion", aiSuggestion,
            "curated", List.of(
                Map.of("name", "Your Signature Bouquet", "price", 85.00, "match", "95%"),
                Map.of("name", "New This Week", "price", 70.00, "match", "88%"),
                Map.of("name", "Fan Favorite", "price", 65.00, "match", "82%")
            )
        ));
    }

    // ── 12. 신상품 추천 ───────────────────────────────────────
    @GetMapping("/new-arrivals")
    public ApiResponse<?> getNewArrivals(@RequestParam(defaultValue = "6") int limit) {
        List<Map<String, Object>> newArrivals = List.of(
            Map.of("id", 301L, "name", "Garden Party Pastel", "price", 85.00, "arrivedDaysAgo", 1, "badge", "NEW"),
            Map.of("id", 302L, "name", "Tropical Paradise Mix", "price", 95.00, "arrivedDaysAgo", 2, "badge", "NEW"),
            Map.of("id", 303L, "name", "Moody Midnight Blues", "price", 110.00, "arrivedDaysAgo", 3, "badge", "NEW"),
            Map.of("id", 304L, "name", "Bohemian Wildflowers", "price", 70.00, "arrivedDaysAgo", 5, "badge", "NEW"),
            Map.of("id", 305L, "name", "Celestial White Collection", "price", 130.00, "arrivedDaysAgo", 6, "badge", "NEW"),
            Map.of("id", 306L, "name", "Spring Delight Petite", "price", 55.00, "arrivedDaysAgo", 7, "badge", "NEW")
        );
        return ApiResponse.ok(Map.of("newArrivals", newArrivals.subList(0, Math.min(limit, newArrivals.size())), "updatedAt", java.time.LocalDate.now().toString()));
    }

    // ── 13. 베스트셀러 목록 ───────────────────────────────────
    @GetMapping("/bestsellers")
    public ApiResponse<?> getBestsellers(@RequestParam(defaultValue = "all") String period,
                                          @RequestParam(defaultValue = "5") int limit) {
        List<Map<String, Object>> bestsellers = List.of(
            Map.of("rank", 1, "id", 1L, "name", "Classic Red Dozen Roses", "price", 89.00, "sold", 1247, "rating", 4.9),
            Map.of("rank", 2, "id", 2L, "name", "Sunflower Happiness", "price", 60.00, "sold", 983, "rating", 4.8),
            Map.of("rank", 3, "id", 3L, "name", "Pink Peony Delight", "price", 110.00, "sold", 754, "rating", 4.9),
            Map.of("rank", 4, "id", 4L, "name", "White Lily Serenity", "price", 95.00, "sold", 631, "rating", 4.7),
            Map.of("rank", 5, "id", 5L, "name", "Rainbow Spring Mix", "price", 70.00, "sold", 598, "rating", 4.8)
        );
        return ApiResponse.ok(Map.of("period", period, "bestsellers", bestsellers.subList(0, Math.min(limit, bestsellers.size()))));
    }

    // ── 14. 특가 상품 (Flash Deals) ───────────────────────────
    @GetMapping("/flash-deals")
    public ApiResponse<?> getFlashDeals() {
        java.time.LocalDateTime expiresAt = java.time.LocalDateTime.now().plusHours(4);
        List<Map<String, Object>> deals = List.of(
            Map.of("id", 401L, "name", "Same-Day Rose Bundle", "originalPrice", 99.00, "salePrice", 74.00, "discount", "25%", "quantityLeft", 8),
            Map.of("id", 402L, "name", "Mixed Seasonal Flash Pack", "originalPrice", 80.00, "salePrice", 55.00, "discount", "31%", "quantityLeft", 12),
            Map.of("id", 403L, "name", "Premium White Lily Deal", "originalPrice", 120.00, "salePrice", 85.00, "discount", "29%", "quantityLeft", 5)
        );
        return ApiResponse.ok(Map.of("flashDeals", deals, "expiresAt", expiresAt.toString(), "notice", "Quantities limited — order now!"));
    }

    // ── 15. 꽃다발 패키지 추천 ────────────────────────────────
    @GetMapping("/bundles")
    public ApiResponse<?> getBundles(@RequestParam(defaultValue = "any") String occasion) {
        List<Map<String, Object>> bundles = List.of(
            Map.of("id", 501L, "name", "Romance Bundle", "items", List.of("Red Roses", "Chocolates", "Card"), "bundlePrice", 98.00, "savings", "$14"),
            Map.of("id", 502L, "name", "Celebration Bundle", "items", List.of("Mixed Bouquet", "Balloon", "Card"), "bundlePrice", 85.00, "savings", "$10"),
            Map.of("id", 503L, "name", "Sympathy Bundle", "items", List.of("White Lilies", "Vase", "Card"), "bundlePrice", 115.00, "savings", "$18"),
            Map.of("id", 504L, "name", "Wedding Day Bundle", "items", List.of("Bridal Bouquet", "Boutonniere", "Corsage"), "bundlePrice", 225.00, "savings", "$30"),
            Map.of("id", 505L, "name", "Subscription Starter Pack", "items", List.of("Weekly Bouquet x4", "Vase"), "bundlePrice", 199.00, "savings", "$40")
        );
        return ApiResponse.ok(Map.of("occasion", occasion, "bundles", bundles));
    }

    // ── 16. 꽃 관리 팁 (Ollama) ───────────────────────────────
    @GetMapping("/care-tips/{productId}")
    public ApiResponse<?> getCareTips(@PathVariable Long productId) {
        String prompt = "Give 5 professional flower care tips for a fresh cut bouquet. Be specific: water change frequency, stem cutting angle, temperature, avoid fruits/direct sun, vase cleaning.";
        String tips = ollama.generate(prompt);
        if (tips.isEmpty()) {
            tips = "1) Change water every 2 days. 2) Cut stems at 45° angle. 3) Keep away from direct sunlight. 4) Remove leaves below waterline. 5) Keep away from fruits (ethylene gas).";
        }
        return ApiResponse.ok(Map.of(
            "productId", productId,
            "aiCareTips", tips,
            "quickTips", List.of(
                Map.of("tip", "Change water every 2 days", "icon", "💧"),
                Map.of("tip", "Cut stems at 45° angle", "icon", "✂️"),
                Map.of("tip", "Keep below 70°F (21°C)", "icon", "🌡️"),
                Map.of("tip", "Remove submerged leaves", "icon", "🌿"),
                Map.of("tip", "Avoid direct sunlight", "icon", "☀️")
            )
        ));
    }

    // ── 17. AI 플로리스트 상담 ────────────────────────────────
    @PostMapping("/ask-florist")
    public ApiResponse<?> askFlorist(@RequestBody Map<String, Object> body) {
        String question = (String) body.getOrDefault("question", "What flowers should I get?");
        String prompt = "You are a warm, expert florist in Montvale, NJ. A customer asks: \"" + question
            + "\"\nGive a helpful, personalized answer. Mention specific flower names, care tips, and budget options if relevant. Keep it conversational and friendly.";
        String answer = ollama.generate(prompt);
        if (answer.isEmpty()) {
            answer = "Great question! I'd love to help you find the perfect flowers. Could you tell me more about the occasion and your budget? In the meantime, our classic red roses ($85) or seasonal mixed bouquets ($65) are always crowd-pleasers!";
        }
        return ApiResponse.ok(Map.of("question", question, "floristAdvice", answer, "askTime", java.time.LocalDateTime.now().toString()));
    }

    // ── 18. 색상 팔레트 추천 ──────────────────────────────────
    @GetMapping("/color-palette")
    public ApiResponse<?> getColorPalette(@RequestParam(defaultValue = "romantic") String mood) {
        Map<String, Map<String, Object>> palettes = new HashMap<>();
        palettes.put("romantic", Map.of("primary", "#E8003D", "secondary", "#FF6B9D", "accent", "#FFF0F3",
            "flowers", List.of("Red Roses", "Pink Peonies", "White Baby's Breath"), "mood", "Passionate & Loving"));
        palettes.put("serene", Map.of("primary", "#C8E6C9", "secondary", "#B3D9FF", "accent", "#F3F4FF",
            "flowers", List.of("White Lilies", "Blue Iris", "Lavender"), "mood", "Calm & Peaceful"));
        palettes.put("vibrant", Map.of("primary", "#FFD600", "secondary", "#FF5722", "accent", "#E040FB",
            "flowers", List.of("Sunflowers", "Orange Gerbera", "Purple Statice"), "mood", "Joyful & Energetic"));
        palettes.put("earthy", Map.of("primary", "#795548", "secondary", "#A5D6A7", "accent", "#FFF9C4",
            "flowers", List.of("Dahlias", "Marigolds", "Dried Wheat"), "mood", "Natural & Grounded"));
        return ApiResponse.ok(Map.of("mood", mood, "palette", palettes.getOrDefault(mood, palettes.get("romantic"))));
    }

    // ── 19. 행사 감정 매핑 ────────────────────────────────────
    @GetMapping("/sentiment/{occasion}")
    public ApiResponse<?> getSentiment(@PathVariable String occasion) {
        Map<String, Map<String, Object>> sentiments = Map.of(
            "birthday", Map.of("emotions", List.of("joy", "celebration", "warmth"), "colorTheme", "bright", "flowerMood", "cheerful", "message", "Celebrate another year of awesomeness!"),
            "wedding", Map.of("emotions", List.of("love", "commitment", "elegance"), "colorTheme", "white/blush", "flowerMood", "romantic", "message", "A perfect beginning to forever"),
            "sympathy", Map.of("emotions", List.of("comfort", "peace", "respect"), "colorTheme", "soft/white", "flowerMood", "serene", "message", "Our thoughts are with you"),
            "anniversary", Map.of("emotions", List.of("romance", "gratitude", "devotion"), "colorTheme", "red/gold", "flowerMood", "passionate", "message", "Celebrating years of beautiful love"),
            "graduation", Map.of("emotions", List.of("pride", "achievement", "hope"), "colorTheme", "bold/colorful", "flowerMood", "triumphant", "message", "The world is yours — congratulations!")
        );
        Map<String, Object> defaultSentiment = Map.of("emotions", List.of("thoughtfulness"), "colorTheme", "mixed", "flowerMood", "warm", "message", "A gift of flowers speaks from the heart");
        return ApiResponse.ok(Map.of("occasion", occasion, "sentiment", sentiments.getOrDefault(occasion, defaultSentiment)));
    }

    // ── 20. AI 카드 메시지 추천 ───────────────────────────────
    @GetMapping("/gift-message/{productId}")
    public ApiResponse<?> getGiftMessage(@PathVariable Long productId,
                                          @RequestParam(defaultValue = "birthday") String occasion) {
        String prompt = "Write 3 short, heartfelt gift card messages for a " + occasion + " flower bouquet. Each should be 1-2 sentences, warm and personal. Number them 1, 2, 3.";
        String aiMessages = ollama.generate(prompt);
        List<String> fallbackMessages;
        switch (occasion) {
            case "wedding" -> fallbackMessages = List.of("Wishing you a lifetime of love and happiness!", "May your love bloom like these flowers.", "To a beautiful new chapter together.");
            case "sympathy" -> fallbackMessages = List.of("Thinking of you with love.", "May these flowers bring a moment of peace.", "You are in our hearts.");
            case "anniversary" -> fallbackMessages = List.of("Every year with you is a blessing.", "Still falling for you, always.", "Here's to many more beautiful years.");
            default -> fallbackMessages = List.of("Wishing you a wonderful day!", "Sending you love and sunshine.", "You deserve all the beautiful things in life.");
        }
        return ApiResponse.ok(Map.of("productId", productId, "occasion", occasion,
            "aiMessages", aiMessages.isEmpty() ? String.join("\n", fallbackMessages) : aiMessages,
            "quickMessages", fallbackMessages));
    }

    // ── 21. 수령인별 추천 ─────────────────────────────────────
    @GetMapping("/by-recipient")
    public ApiResponse<?> getByRecipient(@RequestParam(defaultValue = "her") String recipient) {
        Map<String, List<Map<String, Object>>> recipientMap = Map.of(
            "her", List.of(
                Map.of("name", "Romantic Rose Bouquet", "price", 89.00, "note", "Timeless classic for her"),
                Map.of("name", "Pink Peony Paradise", "price", 110.00, "note", "Her favorite indulgence"),
                Map.of("name", "Blush Garden Dreams", "price", 95.00, "note", "Soft & feminine beauty")
            ),
            "him", List.of(
                Map.of("name", "Bold Tropical Mix", "price", 75.00, "note", "Striking, masculine arrangement"),
                Map.of("name", "Succulent & Bloom", "price", 65.00, "note", "Low-maintenance, modern"),
                Map.of("name", "Sunflower Statement", "price", 70.00, "note", "Bright and uplifting")
            ),
            "parents", List.of(
                Map.of("name", "Classic Garden Collection", "price", 120.00, "note", "Timeless elegance"),
                Map.of("name", "Fruit & Flower Basket", "price", 95.00, "note", "A thoughtful gesture"),
                Map.of("name", "Fragrant Lily Bundle", "price", 105.00, "note", "Long-lasting fragrance")
            ),
            "friend", List.of(
                Map.of("name", "Cheerful Daisy Mix", "price", 60.00, "note", "Fun and friendly"),
                Map.of("name", "Rainbow Spring Bouquet", "price", 70.00, "note", "Colorful and joyful"),
                Map.of("name", "Sunflower Happy Pack", "price", 65.00, "note", "Guaranteed to make them smile")
            )
        );
        List<Map<String, Object>> result = recipientMap.getOrDefault(recipient, recipientMap.get("her"));
        return ApiResponse.ok(Map.of("recipient", recipient, "recommendations", result));
    }

    // ── 22. 당일 배송 가능 상품 ───────────────────────────────
    @GetMapping("/delivery-guarantee")
    public ApiResponse<?> getDeliveryGuarantee(@RequestParam(required = false) String zip,
                                                @RequestParam(defaultValue = "today") String deliveryDate) {
        String cutoffTime = "2:00 PM";
        List<Map<String, Object>> available = List.of(
            Map.of("id", 1L, "name", "Classic Red Roses", "price", 85.00, "deliveryWindow", "2PM-6PM", "inStock", true),
            Map.of("id", 2L, "name", "Sunflower Bunch", "price", 60.00, "deliveryWindow", "12PM-4PM", "inStock", true),
            Map.of("id", 5L, "name", "Mixed Spring Bouquet", "price", 70.00, "deliveryWindow", "2PM-6PM", "inStock", true),
            Map.of("id", 7L, "name", "White Lily Arrangement", "price", 95.00, "deliveryWindow", "3PM-6PM", "inStock", true)
        );
        return ApiResponse.ok(Map.of(
            "zip", zip != null ? zip : "all areas",
            "deliveryDate", deliveryDate,
            "orderCutoff", cutoffTime,
            "availableProducts", available,
            "guarantee", "Order by " + cutoffTime + " for same-day delivery"
        ));
    }

    // ── 23. 친환경/지속가능 꽃 추천 ──────────────────────────
    @GetMapping("/eco-friendly")
    public ApiResponse<?> getEcoFriendly() {
        List<Map<String, Object>> ecoProducts = List.of(
            Map.of("name", "Local Wildflower Meadow", "price", 65.00, "eco", List.of("locally grown", "no pesticides", "biodegradable wrap"), "certifiedOrganic", true),
            Map.of("name", "Potted Herb Garden", "price", 45.00, "eco", List.of("zero waste", "edible", "reusable pot"), "certifiedOrganic", true),
            Map.of("name", "Dried Pampas Bundle", "price", 55.00, "eco", List.of("zero water", "lasts months", "no chemicals"), "certifiedOrganic", false),
            Map.of("name", "Seed Packet Bouquet", "price", 40.00, "eco", List.of("plantable seeds included", "minimal packaging"), "certifiedOrganic", true)
        );
        return ApiResponse.ok(Map.of(
            "ecoProducts", ecoProducts,
            "ourCommitment", "We source from local NJ farms and use compostable packaging for all orders",
            "carbonNeutral", true
        ));
    }

    // ── 24. 프리미엄 컬렉션 ───────────────────────────────────
    @GetMapping("/premium")
    public ApiResponse<?> getPremiumCollection() {
        List<Map<String, Object>> premium = List.of(
            Map.of("id", 601L, "name", "Grand Luxury Rose Tower", "price", 350.00, "stems", 100, "features", List.of("Premium Ecuadorian roses", "Crystal vase", "Satin ribbon")),
            Map.of("id", 602L, "name", "Orchid Elegance Display", "price", 280.00, "stems", 15, "features", List.of("Phalaenopsis orchids", "Handcrafted ceramic pot", "Lasts 8 weeks")),
            Map.of("id", 603L, "name", "Blush Peony Garden", "price", 245.00, "stems", 30, "features", List.of("Premium peonies", "Designer packaging", "Personal florist note")),
            Map.of("id", 604L, "name", "Signature Florist Collection", "price", 199.00, "stems", 25, "features", List.of("Florist curated", "Seasonal premium blooms", "Luxury box")),
            Map.of("id", 605L, "name", "Wedding Centerpiece Grand", "price", 400.00, "stems", 60, "features", List.of("Event-grade blooms", "Custom design consultation", "Setup included"))
        );
        return ApiResponse.ok(Map.of("premiumCollection", premium, "tier", "LUXURY", "freeDelivery", true));
    }

    // ── 25. 맞춤 꽃다발 AI 구성 ───────────────────────────────
    @PostMapping("/custom-bouquet")
    public ApiResponse<?> customBouquet(@RequestBody Map<String, Object> body) {
        String occasion = (String) body.getOrDefault("occasion", "birthday");
        String budget = body.getOrDefault("budget", "100").toString();
        String colorPref = (String) body.getOrDefault("colorPreference", "any");
        String recipientNote = (String) body.getOrDefault("recipientNote", "");
        String prompt = "Design a custom flower bouquet:\n- Occasion: " + occasion
            + "\n- Budget: $" + budget + "\n- Color preference: " + colorPref
            + "\n- Note about recipient: " + recipientNote
            + "\nProvide: bouquet name, exact flowers and quantities, arrangement style, care note, and estimated price breakdown.";
        String design = ollama.generate(prompt);
        if (design.isEmpty()) {
            design = "Custom Bouquet: 6 Red Roses + 4 White Lilies + Baby's Breath filler, wrapped in kraft paper with satin ribbon. Estimated $" + budget + ".";
        }
        return ApiResponse.ok(Map.of(
            "customDesign", design,
            "input", Map.of("occasion", occasion, "budget", budget, "color", colorPref),
            "estimatedReady", "Order by 12PM for same-day creation",
            "orderNote", "Our florist will contact you to confirm the final design"
        ));
    }
}
