package kz.konturai.parser.controller;

import jakarta.validation.Valid;
import kz.konturai.parser.dto.targeting.AdCreativeDto;
import kz.konturai.parser.dto.targeting.CreativeRequest;
import kz.konturai.parser.dto.targeting.MarketingAnalysisDto;
import kz.konturai.parser.dto.targeting.MarketingStrategyDto;
import kz.konturai.parser.dto.targeting.StrategyRequest;
import kz.konturai.parser.dto.targeting.TargetingLaunchResultDto;
import kz.konturai.parser.dto.targeting.TopicRequest;
import kz.konturai.parser.service.AiTargetingSystemService;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Stateless AI Targeting System API.
 *
 * Flow: POST /analysis → POST /strategy → POST /creative
 *
 * No database involved — each endpoint takes the previous step's output
 * as part of the request body and enriches it with AI-generated content.
 */
@RestController
@RequestMapping("/api/targeting")
@RequiredArgsConstructor
public class AiTargetingSystemController {

    private static final Logger logger = LoggerFactory.getLogger(AiTargetingSystemController.class);

    private final AiTargetingSystemService aiTargetingSystemService;

    /**
     * STEP 1 — Marketing Analysis.
     *
     * Accepts a business topic and returns a structured marketing analysis
     * (target audience, platforms, budget, key messages, etc.).
     *
     * POST /api/targeting/analysis
     * Body: { "topic": "детский сад в Алматы" }
     */
    @PostMapping("/analysis")
    public ResponseEntity<MarketingAnalysisDto> generateAnalysis(
            @RequestBody @Valid TopicRequest request) {

        logger.info("POST /api/targeting/analysis — topic: {}", request.getTopic());
        MarketingAnalysisDto result = aiTargetingSystemService.generateAnalysis(request.getTopic());
        return ResponseEntity.ok(result);
    }

    /**
     * STEP 2 — Marketing Strategy.
     *
     * Accepts the full analysis DTO and returns a 3-phase 30-day campaign strategy
     * with ad creatives brief and expected KPIs.
     *
     * POST /api/targeting/strategy
     * Body: { "analysis": { ...MarketingAnalysisDto... } }
     */
    @PostMapping("/strategy")
    public ResponseEntity<MarketingStrategyDto> generateStrategy(
            @RequestBody @Valid StrategyRequest request) {

        logger.info("POST /api/targeting/strategy — topic: {}",
                request.getAnalysis().getTopic());
        MarketingStrategyDto result = aiTargetingSystemService.generateStrategy(request.getAnalysis());
        return ResponseEntity.ok(result);
    }

    /**
     * STEP 3 — Ad Creative.
     *
     * Accepts a creative brief (captionIdea + full analysis + full strategy)
     * and returns a ready-to-launch ad post: headline, caption, hashtags,
     * CTA button, and targeting settings.
     *
     * POST /api/targeting/creative
     * Body: {
     *   "captionIdea": "string",
     *   "analysis": { ...MarketingAnalysisDto... },
     *   "strategy": { ...MarketingStrategyDto... }
     * }
     */
    @PostMapping("/creative")
    public ResponseEntity<AdCreativeDto> generateCreative(
            @RequestBody @Valid CreativeRequest request) {

        logger.info("POST /api/targeting/creative — captionIdea: {}", request.getCaptionIdea());
        AdCreativeDto result = aiTargetingSystemService.generateCreative(
                request.getCaptionIdea(),
                request.getAnalysis(),
                request.getStrategy());
        return ResponseEntity.ok(result);
    }

    /**
     * STEP V3 — Launch Targeting from existing V3 Strategy.
     *
     * Берёт готовую V3-стратегию из MongoDB, генерирует настройки таргетинга
     * через AI на основе V3-анализа и публикует первый пост из postCalendar в Facebook.
     *
     * Требования: стратегия должна иметь статус "completed" и непустой postCalendar.
     *
     * POST /api/targeting/launch/{strategyId}
     */
    @PostMapping("/launch/{strategyId}")
    public ResponseEntity<TargetingLaunchResultDto> launchFromStrategy(
            @PathVariable String strategyId) {

        logger.info("POST /api/targeting/launch/{} — launching targeting from V3 strategy", strategyId);
        TargetingLaunchResultDto result = aiTargetingSystemService.launchTargetingFromStrategy(strategyId);
        return ResponseEntity.ok(result);
    }
}
