package com.moka.gdtauto.controller;

import java.util.List;

import org.springaicommunity.mcp.annotation.McpTool;
import org.springaicommunity.mcp.annotation.McpToolParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.moka.gdtauto.common.Constant;
import com.moka.gdtauto.common.Result;
import com.moka.gdtauto.entity.AdPlan;
import com.moka.gdtauto.entity.AdPlanConf;
import com.moka.gdtauto.service.AdPlanConfService;
import com.moka.gdtauto.service.AdPlanService;

@Component
@RequestMapping("/mcp")
public class McpController {
    @Autowired
    private AdPlanService adPlanService;
    @Autowired
    private AdPlanConfService adPlanConfService;

    @McpTool(name = "get-plans-page-by-conf-id", description = """
            根据广告配置ID分页获取广告列表
            注意：响应[bidAmount,dailyBudget,cost,conversionsCost,scanFollowUserCost,reqIncomeVal1,repIncomeVal1]这写字段单位是分，需转化为元;
            字段说明：bidAmount出价、dailyBudget每日预算、cost消耗、conversionsCost转化消耗、scanFollowUserCost进粉消耗、reqIncomeVal1 广告播放口径的首日广告变现金额、repIncomeVal1 转化回传口径首日广告变现金额、deepConversionWorthRate期望ROI、reqIncomeRoi1 广告播放口径的首日广告变现金额ROI、repIncomeRoi1 转化回传口径首日广告变现金额ROI
            configuredStatus广告配置状态:AD_STATUS_NORMAL=有效; AD_STATUS_SUSPEND=暂停
            响应success=true表示获取成功
            """)
    public Result<Page<AdPlan>> getPlansByConfId(
            @McpToolParam(description = "广告配置ID", required = true) Long adPlanConfId,
            @McpToolParam(description = "页码", required = true) Integer page,
            @McpToolParam(description = "每页数量", required = true) Integer size) {
        AdPlanConf adPlanConf = adPlanConfService.getOne(new LambdaQueryWrapper<AdPlanConf>()
                .eq(AdPlanConf::getId, adPlanConfId)
                .eq(AdPlanConf::getDeleted, 0));
        if (adPlanConf == null) {
            return Result.fail("广告配置不存在");
        }
        Page<AdPlan> plans = adPlanService.lambdaQuery()
                .eq(AdPlan::getDeleted, 0)
                .eq(AdPlan::getAdPlanConfId, adPlanConfId)
                .orderByDesc(AdPlan::getId)
                .page(new Page<>(page, size));
        return Result.success(plans);
    }

    @McpTool(name = "get-adgrop", description = """
                根据广告ID获取广告信息
                响应success=true表示获取成功
                注意：响应[bidAmount,dailyBudget,cost,conversionsCost,scanFollowUserCost,reqIncomeVal1,repIncomeVal1]这写字段单位是分，需转化为元;
                字段说明：bidAmount出价、dailyBudget每日预算、cost消耗、conversionsCost转化消耗、scanFollowUserCost进粉消耗、reqIncomeVal1 广告播放口径的首日广告变现金额、repIncomeVal1 转化回传口径首日广告变现金额、deepConversionWorthRate期望ROI、reqIncomeRoi1 广告播放口径的首日广告变现金额ROI、repIncomeRoi1 转化回传口径首日广告变现金额ROI
                configuredStatus广告配置状态:AD_STATUS_NORMAL=有效; AD_STATUS_SUSPEND=暂停
            """)
    public Result<AdPlan> getAdGroup(
            @McpToolParam(description = "广告ID", required = true) Long adgroupId) {
        AdPlan plan = adPlanService.lambdaQuery()
                .eq(AdPlan::getAdgroupId, adgroupId)
                .one();
        if (plan != null) {
            plan.setSystemStatus(Constant.getAdGroupStatusValue(plan.getSystemStatus()));
            return Result.success(plan);
        } else {
            return Result.fail("广告组不存在");
        }
    }

    @McpTool(name = "update-adgroup-daily-budget", description = "更新广告每日预算；响应success=true表示操作成功")
    public Result<AdPlan> updateAdgroupDailyBudget(
            @McpToolParam(description = "广告ID", required = true) Long adgroupId,
            @McpToolParam(description = "每日预算(元)", required = true) Long dailyBudgetYuan) {
        AdPlan plan = adPlanService.lambdaQuery().eq(AdPlan::getAdgroupId, adgroupId).one();
        if (plan != null) {
            Long adPlanConfId = plan.getAdPlanConfId();
            AdPlanConf adPlanConf = adPlanConfService.getOne(new LambdaQueryWrapper<AdPlanConf>()
                    .eq(AdPlanConf::getId, adPlanConfId)
                    .eq(AdPlanConf::getDeleted, 0));
            try {
                adPlanService.updateAdgroupDailyBudget(adPlanConf, plan, dailyBudgetYuan * 100);
            } catch (Exception e) {
                return Result.fail("更新广告每日预算失败 e=" + e.getMessage());
            }
            return Result.success();
        } else {
            return Result.fail("广告不存在");
        }
    }

    @McpTool(name = "suspend-adgroup", description = "暂停广告；响应success=true表示操作成功")
    public Result<AdPlan> suspendAdgroup(
            @McpToolParam(description = "广告ID", required = true) Long adgroupId) {
        AdPlan plan = adPlanService.lambdaQuery().eq(AdPlan::getAdgroupId, adgroupId).one();
        if (plan != null) {
            Long adPlanConfId = plan.getAdPlanConfId();
            AdPlanConf adPlanConf = adPlanConfService.getOne(new LambdaQueryWrapper<AdPlanConf>()
                    .eq(AdPlanConf::getId, adPlanConfId)
                    .eq(AdPlanConf::getDeleted, 0));
            try {
                adPlanConfService.gdtSuspendByPlans(adPlanConf, List.of(plan));
            } catch (Exception e) {
                return Result.fail("暂停广告失败 e=" + e.getMessage());
            }
            return Result.success();
        }
        return Result.fail("广告不存在");
    }

    @McpTool(name = "delete-adgroup", description = "删除广告；响应success=true表示操作成功")
    public Result<AdPlan> deleteAdgroup(
            @McpToolParam(description = "广告ID", required = true) Long adgroupId) {
        AdPlan plan = adPlanService.lambdaQuery().eq(AdPlan::getAdgroupId, adgroupId).one();
        if (plan != null) {
            Long adPlanConfId = plan.getAdPlanConfId();
            AdPlanConf adPlanConf = adPlanConfService.getOne(new LambdaQueryWrapper<AdPlanConf>()
                    .eq(AdPlanConf::getId, adPlanConfId)
                    .eq(AdPlanConf::getDeleted, 0));
            try {
                adPlanConfService.gdtDeleteByPlanIds(adPlanConf, List.of(plan.getId()));
            } catch (Exception e) {
                return Result.fail("删除广告失败 e=" + e.getMessage());
            }
            return Result.success(plan);
        }
        return Result.fail("广告不存在");
    }
}
