package kz.konturai.parser.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import kz.konturai.parser.dto.MarketingAnalysisV3Request;
import kz.konturai.parser.dto.MarketingAnalysisV3Result;
import kz.konturai.parser.dto.targeting.AudienceProfileDto;
import kz.konturai.parser.dto.targeting.HypothesisCellDto;
import kz.konturai.parser.dto.targeting.HypothesisMatrixDto;
import kz.konturai.parser.dto.targeting.LandingPageAuditDto;
import kz.konturai.parser.dto.targeting.RiskAnalysisDto;
import kz.konturai.parser.dto.targeting.TargetingBudgetDto;
import kz.konturai.parser.dto.targeting.TargetingRecommendationDto;
import kz.konturai.parser.enums.AverageCheck;
import kz.konturai.parser.model.MarketingStrategy;
import org.junit.jupiter.api.Test;

import java.lang.reflect.Method;
import java.util.List;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;

class AiTargetingSystemServiceManagementLayerTest {

    private final AiTargetingSystemService service =
            new AiTargetingSystemService(null, new ObjectMapper(), null, null, null, null);

    @Test
    void validateAndNormalizeRecommendation_shouldFillManagementBlocksAndClampValues() throws Exception {
        MarketingAnalysisV3Request req = new MarketingAnalysisV3Request();
        req.setBusinessNiche("Стоматология");
        req.setPromotionCities(List.of("Алматы"));
        req.setAverageCheck(AverageCheck.HIGH);
        req.setUserSocialLinks(List.of("https://site.kz", "https://instagram.com/brand"));

        MarketingAnalysisV3Result.CompetitionIntensity intensity = new MarketingAnalysisV3Result.CompetitionIntensity();
        intensity.setCiiIndex(82);
        intensity.setIntensityLabel("Высокий");

        MarketingAnalysisV3Result.CompetitorProfile competitor = new MarketingAnalysisV3Result.CompetitorProfile();
        competitor.setName("Strong Clinic");
        competitor.setFollowers(12000);
        competitor.setStrengths(List.of("Много видео-отзывов", "Сильный social proof"));

        MarketingAnalysisV3Result res = new MarketingAnalysisV3Result();
        res.setCompetitionIntensity(intensity);
        res.setCompetitorMap(List.of(competitor));

        MarketingStrategy strategy = new MarketingStrategy();
        strategy.setScoringModelName("TRUST");
        strategy.setScoringModelTitle("Trust");
        strategy.setStatus("completed");
        strategy.setDurationWeeks(4);

        TargetingRecommendationDto partial = TargetingRecommendationDto.builder()
                .recommendedType("MIXED")
                .recommendedTypeLabel("Комбинированный таргетинг")
                .typeRationale("Базовая логика")
                .campaignObjective("LEADS")
                .campaignObjectiveLabel("Лиды")
                .campaignObjectiveRationale("Нужно больше заявок")
                .audienceProfile(AudienceProfileDto.builder()
                        .primarySegment("Жители Алматы")
                        .ageRange("25-44")
                        .gender("Женщины 60%, Мужчины 40%")
                        .build())
                .budgetRecommendation(TargetingBudgetDto.builder()
                        .dailyBudget("10 000 KZT")
                        .monthlyBudget("300 000 KZT")
                        .build())
                .hypothesisMatrix(HypothesisMatrixDto.builder()
                        .rowCount(1)
                        .colCount(1)
                        .rows(List.of("Только один angle"))
                        .cols(List.of("Только один visual"))
                        .matrix(List.of(HypothesisCellDto.builder()
                                .hookIndex(0)
                                .visualIndex(0)
                                .specificAdIdea("")
                                .build()))
                        .build())
                .lpAudit(LandingPageAuditDto.builder()
                        .matchScore(140)
                        .criticalFixes(List.of())
                        .trustBoosters(List.of())
                        .build())
                .risks(RiskAnalysisDto.builder()
                        .policyRiskLevel("высокий")
                        .moderationTriggers(List.of())
                        .build())
                .suggestedRules(List.of())
                .build();

        Method method = AiTargetingSystemService.class.getDeclaredMethod(
                "validateAndNormalizeRecommendation",
                TargetingRecommendationDto.class,
                MarketingAnalysisV3Request.class,
                MarketingAnalysisV3Result.class,
                MarketingStrategy.class);
        method.setAccessible(true);

        TargetingRecommendationDto normalized = (TargetingRecommendationDto) method.invoke(
                service, partial, req, res, strategy);

        assertNotNull(normalized.getPixelHealth());
        assertNotNull(normalized.getFunnelStrategy());
        assertNotNull(normalized.getHypothesisMatrix());
        assertNotNull(normalized.getLpAudit());
        assertNotNull(normalized.getScalingPlan());
        assertNotNull(normalized.getRisks());
        assertEquals(4, normalized.getHypothesisMatrix().getRowCount());
        assertEquals(4, normalized.getHypothesisMatrix().getColCount());
        assertEquals(16, normalized.getHypothesisMatrix().getMatrix().size());
        assertEquals(100, normalized.getLpAudit().getMatchScore());
        assertEquals(3, normalized.getLpAudit().getCriticalFixes().size());
        assertEquals(3, normalized.getLpAudit().getTrustBoosters().size());
        assertEquals(3, normalized.getSuggestedRules().size());
        assertEquals(3, normalized.getRisks().getModerationTriggers().size());
        assertTrue(normalized.getRisks().getPolicyRiskLevel().startsWith("High"));
    }

    @Test
    void buildEnhancedFullContext_shouldIncludeContextEnrichment() throws Exception {
        MarketingAnalysisV3Request req = new MarketingAnalysisV3Request();
        req.setBusinessNiche("Онлайн-курсы");
        req.setProductName("Course X");
        req.setGoal("Рост лидов");
        req.setPromotionCities(List.of("Астана"));
        req.setUserSocialLinks(List.of("https://site.kz", "https://instagram.com/coursex"));

        MarketingAnalysisV3Result.CompetitionIntensity intensity = new MarketingAnalysisV3Result.CompetitionIntensity();
        intensity.setCiiIndex(68);
        intensity.setIntensityLabel("Средний");

        MarketingAnalysisV3Result.ContentProfile contentProfile = new MarketingAnalysisV3Result.ContentProfile();
        contentProfile.setVideoShare(74.0);

        MarketingAnalysisV3Result.CompetitorProfile competitor = new MarketingAnalysisV3Result.CompetitorProfile();
        competitor.setName("Competitor A");
        competitor.setFollowers(9000);
        competitor.setStrengths(List.of("Сильный экспертный контент"));

        MarketingAnalysisV3Result res = new MarketingAnalysisV3Result();
        res.setCompetitionIntensity(intensity);
        res.setContentProfile(contentProfile);
        res.setCompetitorMap(List.of(competitor));

        MarketingStrategy strategy = new MarketingStrategy();
        strategy.setScoringModelName("AUTHORITY");
        strategy.setScoringModelTitle("Authority");
        strategy.setStatus("completed");
        strategy.setDurationWeeks(4);

        Method method = AiTargetingSystemService.class.getDeclaredMethod(
                "buildEnhancedFullContext",
                MarketingAnalysisV3Request.class,
                MarketingAnalysisV3Result.class,
                MarketingStrategy.class);
        method.setAccessible(true);

        String context = (String) method.invoke(service, req, res, strategy);

        assertTrue(context.contains("https://instagram.com/coursex"));
        assertTrue(context.contains("Competitor A"));
        assertTrue(context.contains("AUTHORITY"));
        assertTrue(context.contains("CURRENT DIGITAL ASSETS"));
    }
}
