package com.yice.webadmin.app.controller;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.page.PageMethod;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.yice.common.core.annotation.MyRequestBody;
import com.yice.common.core.constant.ErrorCodeEnum;
import com.yice.common.core.object.*;
import com.yice.common.core.util.MyCommonUtil;
import com.yice.common.core.util.MyModelUtil;
import com.yice.common.core.util.MyPageUtil;
import com.yice.common.log.annotation.OperationLog;
import com.yice.common.log.model.constant.SysOperationLogType;
import com.yice.webadmin.app.config.PythonConfig;
import com.yice.webadmin.app.dto.ModelVersionDto;
import com.yice.webadmin.app.model.ModelVersion;
import com.yice.webadmin.app.service.ModelVersionService;
import com.yice.webadmin.app.service.ProxyPythonService;
import com.yice.webadmin.app.service.TuningRunService;
import com.yice.webadmin.app.vo.ModelVersionVo;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;

/**
 * 模型版本操作控制器类。
 *
 * @author linking
 * @date 2023-04-13
 */
@Api(tags = "模型版本管理接口")
@Slf4j
@RestController
@RequestMapping("/admin/app/modelVersion")
public class ModelVersionController {

    @Autowired
    private ModelVersionService modelVersionService;
    @Autowired
    private PythonConfig pythonConfig;
    @Autowired
    private ProxyPythonService proxyPythonService;
    @Autowired
    private TuningRunService tuningRunService;


    /**
     * 新增模型版本数据。
     *
     * @param modelVersionDto 新增对象。
     * @return 应答结果对象，包含新增对象主键Id。
     */
    @ApiOperationSupport(ignoreParameters = {"modelVersionDto.versionId"})
    @OperationLog(type = SysOperationLogType.ADD)
    @PostMapping("/add")
    public ResponseResult<Long> add(@MyRequestBody ModelVersionDto modelVersionDto) {
        String errorMessage = MyCommonUtil.getModelValidationError(modelVersionDto, false);
        if (errorMessage != null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_VALIDATED_FAILED, errorMessage);
        }
        ModelVersion modelVersion = MyModelUtil.copyTo(modelVersionDto, ModelVersion.class);
        // 验证关联Id的数据合法性
        CallResult callResult = modelVersionService.verifyRelatedData(modelVersion, null);
        if (!callResult.isSuccess()) {
            return ResponseResult.errorFrom(callResult);
        }
        modelVersion = this.tuningRunService.createToModelVersion(modelVersion);
        return ResponseResult.success(modelVersion.getVersionId());
    }

    /**
     * 更新模型版本数据。
     *
     * @param modelVersionDto 更新对象。
     * @return 应答结果对象。
     */
    @OperationLog(type = SysOperationLogType.UPDATE)
    @PostMapping("/update")
    public ResponseResult<Void> update(@MyRequestBody ModelVersionDto modelVersionDto) {
        String errorMessage = MyCommonUtil.getModelValidationError(modelVersionDto, true);
        if (errorMessage != null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_VALIDATED_FAILED, errorMessage);
        }
        ModelVersion modelVersion = MyModelUtil.copyTo(modelVersionDto, ModelVersion.class);
        ModelVersion originalModelVersion = modelVersionService.getById(modelVersion.getVersionId());
        if (originalModelVersion == null) {
            // NOTE: 修改下面方括号中的话述
            errorMessage = "数据验证失败，当前 [数据] 并不存在，请刷新后重试！";
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, errorMessage);
        }
        // 验证关联Id的数据合法性
        CallResult callResult = modelVersionService.verifyRelatedData(modelVersion, originalModelVersion);
        if (!callResult.isSuccess()) {
            return ResponseResult.errorFrom(callResult);
        }
        if (!modelVersionService.update(modelVersion, originalModelVersion)) {
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST);
        }
        return ResponseResult.success();
    }

    /**
     * 删除模型版本数据。
     *
     * @param versionId 删除对象主键Id。
     * @return 应答结果对象。
     */
    @OperationLog(type = SysOperationLogType.DELETE)
    @PostMapping("/delete")
    public ResponseResult<Void> delete(@MyRequestBody Long versionId) {
        if (MyCommonUtil.existBlankArgument(versionId)) {
            return ResponseResult.error(ErrorCodeEnum.ARGUMENT_NULL_EXIST);
        }
        return this.doDelete(versionId);
    }

    /**
     * 列出符合过滤条件的模型管理列表。
     *
     * @return 应答结果对象，包含查询结果集。
     */
    @PostMapping("/change")
    public ResponseResult<String> change(@MyRequestBody Long versionId) throws IOException {
        ModelVersion modelVersion = this.modelVersionService.getById(versionId);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("new_model_name", modelVersion.getVersionName());
        jsonObject.put("new_model_path", modelVersion.getModelUrl());
        jsonObject.put("template", modelVersion.getBasePromptTemplate());
        jsonObject.put("finetuning_type", modelVersion.getModelTrainingMethod());
        String url = this.pythonConfig.getChatAddress() + "llm_model/change";
        String result = proxyPythonService.predictPost(url, jsonObject.toJSONString());
        JSONObject jo = JSON.parseObject(result);
        Integer code = jo.getIntValue("code");
        String msg = jo.getString("msg");
        String data = jo.getString("data");
        if (code != null && code == 200) {
            return ResponseResult.success(msg);
        } else {
            return ResponseResult.create(ErrorCodeEnum.SERVER_INTERNAL_ERROR, msg, data);
        }
    }

    /**
     * 停止指定的LLM模型（Model Worker)
     *
     * @return 应答结果对象，包含查询结果集。
     */
    @PostMapping("/stop")
    public ResponseResult<String> stop() throws IOException {
        String url = this.pythonConfig.getChatAddress() + "llm_model/stop";
        String result = proxyPythonService.predictPost(url, "");
        JSONObject jo = JSON.parseObject(result);
        Integer code = jo.getIntValue("code");
        String msg = jo.getString("msg");
        String data = jo.getString("data");
        if (code != null && code == 200) {
            return ResponseResult.success(msg);
        } else {
            return ResponseResult.create(ErrorCodeEnum.SERVER_INTERNAL_ERROR, msg, data);
        }
    }

    /**
     * 列出当前已加载的模型。
     *
     * @return 应答结果对象，包含查询结果集。
     */
    @PostMapping("/listModels")
    public ResponseResult<JSONArray> listModels() throws IOException {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("controller_address", pythonConfig.getControllerAddress());
        jsonObject.put("placeholder", "string");
        String url = this.pythonConfig.getChatAddress() + "llm_model/list_running_models";
        String result = proxyPythonService.predictPost(url, jsonObject.toJSONString());
        JSONObject jo = JSON.parseObject(result);
        Integer code = jo.getIntValue("code");
        String msg = jo.getString("msg");
        if (code != null && code == 200) {
            return ResponseResult.create(ErrorCodeEnum.NO_ERROR, msg, jo.getJSONArray("data"));
        } else {
            return ResponseResult.create(ErrorCodeEnum.SERVER_INTERNAL_ERROR, msg, null);
        }
    }


    /**
     * 列出符合过滤条件的模型版本列表。
     *
     * @param modelVersionDtoFilter 过滤对象。
     * @param orderParam            排序参数。
     * @param pageParam             分页参数。
     * @return 应答结果对象，包含查询结果集。
     */
    @PostMapping("/list")
    public ResponseResult<MyPageData<ModelVersionVo>> list(
            @MyRequestBody ModelVersionDto modelVersionDtoFilter,
            @MyRequestBody MyOrderParam orderParam,
            @MyRequestBody MyPageParam pageParam) {
        if (pageParam != null) {
            PageMethod.startPage(pageParam.getPageNum(), pageParam.getPageSize());
        }
        ModelVersion modelVersionFilter = MyModelUtil.copyTo(modelVersionDtoFilter, ModelVersion.class);
        String orderBy = MyOrderParam.buildOrderBy(orderParam, ModelVersion.class);
        List<ModelVersion> modelVersionList =
                modelVersionService.getModelVersionListWithRelation(modelVersionFilter, orderBy);
        return ResponseResult.success(MyPageUtil.makeResponseData(modelVersionList, ModelVersion.INSTANCE));
    }

    /**
     * 查看指定模型版本对象详情。
     *
     * @param versionId 指定对象主键Id。
     * @return 应答结果对象，包含对象详情。
     */
    @GetMapping("/view")
    public ResponseResult<ModelVersionVo> view(@RequestParam Long versionId) {
        ModelVersion modelVersion = modelVersionService.getByIdWithRelation(versionId, MyRelationParam.full());
        if (modelVersion == null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST);
        }
        ModelVersionVo modelVersionVo = ModelVersion.INSTANCE.fromModel(modelVersion);
        return ResponseResult.success(modelVersionVo);
    }

    /**
     * 查看指定模型最新版本对象详情。
     *
     * @param modelId 指定对象主键Id。
     * @return 应答结果对象，包含对象详情。
     */
    @GetMapping("/lastModelVersion")
    public ResponseResult<ModelVersionVo> lastModelVersion(@RequestParam Long modelId) {
        ModelVersion modelVersion = this.modelVersionService.lastModelVersion(modelId);
        return ResponseResult.success(ModelVersion.INSTANCE.fromModel(modelVersion));
    }

    private ResponseResult<Void> doDelete(Long versionId) {
        String errorMessage;
        // 验证关联Id的数据合法性
        ModelVersion originalModelVersion = modelVersionService.getById(versionId);
        if (originalModelVersion == null) {
            // NOTE: 修改下面方括号中的话述
            errorMessage = "数据验证失败，当前 [对象] 并不存在，请刷新后重试！";
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, errorMessage);
        }
        if (!modelVersionService.remove(versionId)) {
            errorMessage = "数据操作失败，删除的对象不存在，请刷新后重试！";
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, errorMessage);
        }
        FileUtil.del(originalModelVersion.getModelUrl());
        return ResponseResult.success();
    }
}
