package com.seer.teach.admin.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.seer.teach.admin.request.GenerateTaskReq;
import com.seer.teach.admin.request.TeachTextsQueryReq;
import com.seer.teach.admin.request.TeachTextsReq;
import com.seer.teach.admin.request.TeachTextVideoUpdateReq;
import com.seer.teach.admin.request.UploadTeachVideoReq;
import com.seer.teach.admin.response.TeachTextsResp;
import com.seer.teach.admin.service.AdminTeachTextsService;
import com.seer.teach.admin.service.TeachTextGenerationService;
import com.seer.teach.admin.service.VideoScriptGenerationService;
import com.seer.teach.common.PageListBean;
import com.seer.teach.common.ResultBean;
import com.seer.teach.common.enums.AiScenarioCodeEnum;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 管理端 - 教学文本管理
 * </p>
 *
 * @author Lingma
 * @since 2025-12-04
 */
@RestController
@RequestMapping("/teacher/teach-text")
@RequiredArgsConstructor
@Tag(name = "管理端 - 教学文本管理")
@Validated
public class AdminTeachTextsController {

    private final AdminTeachTextsService adminTeachTextsService;

    private final TeachTextGenerationService teachTextGenerationService;

    private final VideoScriptGenerationService videoScriptGenerationService;

    @Value("${video.upload.path:videos}")
    private String videoUploadPath;

    @PostMapping("/page-list")
    @Operation(summary = "分页查询教学文本列表")
    @SaCheckPermission("teacher:admin:teach-texts:list")
    public ResultBean<PageListBean<TeachTextsResp>> pageTeachTexts(@RequestBody @Validated TeachTextsQueryReq req) {
        IPage<TeachTextsResp> page = adminTeachTextsService.pageTeachTexts(req);
        return ResultBean.success(new PageListBean<>(page));
    }

    @GetMapping("/{id}")
    @Operation(summary = "根据ID获取教学文本详情")
    @SaCheckPermission("teacher:admin:teach-texts:detail")
    public ResultBean<TeachTextsResp> getTeachTextById(@Parameter(description = "教学文本ID") @PathVariable @NotNull(message = "教学文本ID不能为空") Integer id) {
        TeachTextsResp teachText = adminTeachTextsService.getTeachTextById(id);
        return ResultBean.success(teachText);
    }

    @PostMapping
    @Operation(summary = "添加教学文本")
    @SaCheckPermission("teacher:admin:teach-texts:save")
    public ResultBean<Boolean> addTeachText(@Parameter(description = "教学文本信息") @Valid @RequestBody TeachTextsReq req) {
        boolean result = adminTeachTextsService.addTeachText(req);
        return ResultBean.success(result);
    }

    @PutMapping("/{id}")
    @Operation(summary = "更新教学文本信息")
    @SaCheckPermission("teacher:admin:teach-texts:update")
    public ResultBean<Boolean> updateTeachText(@Parameter(description = "教学文本ID") @PathVariable @NotNull(message = "教学文本ID不能为空") Integer id,
                                              @Parameter(description = "教学文本信息") @Valid @RequestBody TeachTextsReq req) {
        boolean result = adminTeachTextsService.updateTeachText(id, req);
        return ResultBean.success(result);
    }

    @PutMapping("/{id}/sort/{sort}")
    @Operation(summary = "更新教学文本的排序")
    @SaCheckPermission("teacher:admin:teach-texts:sort:update")
    public ResultBean<Boolean> updateTeachTextSort(@Parameter(description = "教学文本ID") @PathVariable @NotNull(message = "教学文本ID不能为空") Integer id,
                                                   @PathVariable @NotNull(message = "教学文本的排序") Integer sort) {
        boolean result = adminTeachTextsService.updateTeachTextSort(id, sort);
        return ResultBean.success(result);
    }

    @PutMapping("/{id}/video")
    @Operation(summary = "更新教学文本的视频脚本和URL")
    @SaCheckPermission("teacher:admin:teach-texts:update")
    public ResultBean<Boolean> updateTeachTextVideo(@Parameter(description = "教学文本ID") @PathVariable @NotNull(message = "教学文本ID不能为空") Integer id,
                                                   @Parameter(description = "视频脚本和URL信息") @Valid @RequestBody TeachTextVideoUpdateReq req) {
        boolean result = adminTeachTextsService.updateTeachTextVideo(id, req);
        return ResultBean.success(result);
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除教学文本")
    @SaCheckPermission("teacher:admin:teach-texts:delete")
    public ResultBean<Boolean> deleteTeachText(@Parameter(description = "教学文本ID") @PathVariable @NotNull(message = "教学文本ID不能为空") Integer id) {
        boolean result = adminTeachTextsService.deleteTeachText(id);
        return ResultBean.success(result);
    }

    @PostMapping("/generate-text")
    @Operation(summary = "根据教学目标生成讲课稿")
    @SaCheckPermission("teacher:admin:teach-texts:generate")
    public ResultBean<List<TeachTextsResp>> generateSimilarTeachTexts(
            @Parameter(description = "生成讲课稿参数") @Valid @RequestBody GenerateTaskReq req) {
        req.setUserId(cn.dev33.satoken.stp.StpUtil.getLoginIdAsInt());
        List<TeachTextsResp> result = teachTextGenerationService.generateTeachTexts(req);
        return ResultBean.success(result);
    }

    @PostMapping("/generate-video-script")
    @Operation(summary = "根据讲课稿生成视频脚本")
    @SaCheckPermission("teacher:admin:teach-texts:generate")
    public ResultBean<List<TeachTextsResp>> generateTeachTextVideoScript(@RequestParam("textId") Integer textId) {
        GenerateTaskReq req = new GenerateTaskReq();
        req.setTextId(textId);
        req.setUserId(StpUtil.getLoginIdAsInt());
        req.setScenarioCode(AiScenarioCodeEnum.GENERATE_VIDEO_SCRIPT_FROM_TEACH_TEXTS.getCode());
        List<TeachTextsResp> result = videoScriptGenerationService.generateVideoScripts(req);
        return ResultBean.success(result);
    }

    @PostMapping("/generate-all-text-and-save")
    @Operation(summary = "生成所有讲课稿并保存")
    @SaCheckPermission("teacher:admin:teach-texts:generate")
    public ResultBean<Integer> generateAllTeachTextsAndSave(
            @Parameter(description = "生成讲课稿参数") @Valid @RequestBody GenerateTaskReq req) {
        req.setUserId(cn.dev33.satoken.stp.StpUtil.getLoginIdAsInt());
        Integer result = teachTextGenerationService.generateAndSaveAllTeachTexts(req);
        return ResultBean.success(result);
    }


    @PostMapping("/{textId}/upload-video-update-url")
    @Operation(summary = "上传教学视频")
    @SaCheckPermission("teacher:admin:teach-texts:upload-video")
    public ResultBean<String> uploadTeachVideoAndUpdateUrl(@Parameter(description = "教学文本ID") @PathVariable @NotNull(message = "教学文本ID不能为空") Integer textId,
                                                           @Parameter(description = "上传视频参数") @Valid UploadTeachVideoReq req) {
        return ResultBean.success(adminTeachTextsService.uploadTeachVideoAndUpdateUrl(textId, req.getVideoFile()));
    }
    
    @GetMapping("/{textId}/download-video")
    @Operation(summary = "下载教学视频")
    @SaCheckPermission("teacher:admin:teach-texts:download-video")
    public void downloadTeachVideo(
            @Parameter(description = "教学文本ID") @PathVariable @NotNull(message = "教学文本ID不能为空") Integer textId,
            HttpServletResponse response) {
        adminTeachTextsService.downloadTeachVideo(textId, response);
    }
}