package com.yaoai.api.controller;

import com.yaoai.common.response.ApiResponse;
import com.yaoai.domain.entity.Scene;
import com.yaoai.pipeline.service.AssetGenPipelineService;
import com.yaoai.security.context.TenantContext;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

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

@Tag(name = "场景管理")
@RestController
@RequestMapping("/projects/{projectId}/scenes")
@RequiredArgsConstructor
public class SceneController {

    private final AssetGenPipelineService assetService;

    @Operation(summary = "AI 提取场景列表（从大纲+分集）")
    @PostMapping("/extract")
    public ApiResponse<List<Scene>> extract(@PathVariable Long projectId) {
        return ApiResponse.success(assetService.extractScenes(projectId, TenantContext.get()));
    }

    @Operation(summary = "获取场景列表")
    @GetMapping
    public ApiResponse<List<Scene>> list(@PathVariable Long projectId) {
        return ApiResponse.success(assetService.listScenes(projectId, TenantContext.get()));
    }

    @Operation(summary = "新建/更新场景")
    @PostMapping
    public ApiResponse<Scene> save(@PathVariable Long projectId, @RequestBody Scene req) {
        req.setProjectId(projectId);
        req.setTenantId(TenantContext.get());
        return ApiResponse.success(assetService.saveScene(req));
    }

    @Operation(summary = "为场景生成图片（Seedream）")
    @PostMapping("/{sceneId}/generate-image")
    public ApiResponse<Scene> generateImage(@PathVariable Long projectId,
                                            @PathVariable Long sceneId) {
        return ApiResponse.success(assetService.generateSceneImage(sceneId, TenantContext.get()));
    }

    @Operation(summary = "上传场景图片（手动）")
    @PostMapping(value = "/{sceneId}/upload-image", consumes = "multipart/form-data")
    public ApiResponse<Scene> uploadImage(@PathVariable Long projectId,
                                          @PathVariable Long sceneId,
                                          @RequestPart("file") MultipartFile file) throws IOException {
        String originalName = file.getOriginalFilename() != null ? file.getOriginalFilename() : "image.jpg";
        String ext = originalName.contains(".") ? originalName.substring(originalName.lastIndexOf('.') + 1) : "jpg";
        return ApiResponse.success(assetService.uploadSceneImage(
                sceneId, TenantContext.get(),
                file.getInputStream(), file.getSize(), file.getContentType(), ext));
    }

    @Operation(summary = "删除场景")
    @DeleteMapping("/{sceneId}")
    public ApiResponse<Void> delete(@PathVariable Long projectId, @PathVariable Long sceneId) {
        assetService.deleteScene(sceneId, TenantContext.get());
        return ApiResponse.success();
    }
}
