package kz.konturai.parser.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import kz.konturai.parser.config.TargetingApiConfig;
import kz.konturai.parser.dto.BudgetOptimizationDto;
import kz.konturai.parser.exception.BudgetOptimizationException;
import kz.konturai.parser.model.MarketingAnalysisV3Document;
import kz.konturai.parser.model.TargetingCampaign;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@RequiredArgsConstructor
@Slf4j
public class BudgetOptimizerService {

    private final OpenAIAnalyticsService openAiService;
    private final TargetingApiConfig apiConfig;
    private final ObjectMapper objectMapper;

    public BudgetOptimizationDto optimizeBudget(TargetingCampaign campaign, MarketingAnalysisV3Document analysis) {
        log.info("[BudgetOptimizerService] Optimizing budget for campaign {}", campaign.getId());

        try {
            String systemPrompt = "Ты — медиапланер с опытом работы на рынке Казахстана. Верни только JSON ответ без маркдауна. \n" +
                    "Дано:\n" +
                    " - Общий бюджет: " + campaign.getBudget().getTotalBudget() + " KZT\n" +
                    " - Цель: " + campaign.getObjective() + "\n" +
                    "Рекомендации по рынку Казахстана (используй как базу):\n" +
                    " - Instagram Feed CPM: 1200-2500 KZT\n" +
                    " - TikTok CPM: 400-900 KZT\n" +
                    "Верни JSON со следующей структурой: platformAllocations, dailyBudgetPerPlatform, estimatedImpressions, estimatedClicks, estimatedLeads, estimatedCostPerLead, expectedRoas, riskLevel, riskRationale, schedulingWindows, recommendedBidStrategy, optimizationTips";

            String instruction = "Рассчитай медиаплан на основе бюджета " + campaign.getBudget().getTotalBudget() + " тнг";
            
            String response = openAiService.generateWithInstructionWithModel(
                    "Анализ ниши",
                    instruction,
                    "ru",
                    apiConfig.getAi().getBudgetModel(),
                    systemPrompt,
                    apiConfig.getAi().getMaxBudgetTokens()
            );

            if (response == null || response.isBlank()) {
                throw new BudgetOptimizationException("AI returned empty for budget optimization");
            }
            if (response.startsWith("```json")) {
                response = response.substring(7, response.lastIndexOf("```")).trim();
            }

            return objectMapper.readValue(response, BudgetOptimizationDto.class);
        } catch (Exception e) {
            log.error("Failed to optimize budget", e);
            throw new BudgetOptimizationException("Failed to optimize budget", e);
        }
    }

    public BudgetOptimizationDto rebalanceBudget(String campaignId, BudgetOptimizationDto existingPlan) {
        log.info("[BudgetOptimizerService] Rebalancing budget for campaign {}", campaignId);
        // In a real scenario, this fetches actual insights comparing to expected plan.
        // For now, returning existing plan setup smoothly.
        return existingPlan;
    }
}
