package com.huimv.employment.controller.mcp;

import com.huimv.employment.common.web.R;
import com.huimv.employment.service.draft.McpDraftService;
import com.huimv.employment.service.draft.dto.McpDraftCalculateRequest;
import com.huimv.employment.service.draft.dto.McpDraftCalculateResponse;
import com.huimv.employment.service.draft.dto.McpDraftGenerateRequest;
import com.huimv.employment.service.draft.dto.McpDraftGenerateResponse;
import com.huimv.employment.service.draft.dto.McpDraftInfoResponse;
import com.huimv.employment.service.draft.dto.McpDraftSubmitRequest;
import com.huimv.employment.service.draft.dto.McpDraftSubmitResponse;
import com.huimv.employment.service.draft.dto.McpDraftUpdateRequest;
import com.huimv.employment.service.draft.dto.McpDraftUpdateResponse;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
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;

/**
 * MCP 草稿接口（交互规则 v4 §6.4）。
 * <p>
 * generate 通过 session_id 创建/复用草稿并返回 draft_id + schema（含多工种 worker_groups）；
 * update/info/calculate/submit 须同时传入 session_id 与 draft_id。
 * 鉴权见 {@code fe.internal.ai-key} 与 {@link com.huimv.employment.security.McpAuthFilter}。
 * </p>
 */
@RestController
@RequestMapping("/api/mcp/draft")
@Tag(name = "MCP-草稿", description = "智能体草稿 generate/update/info/calculate/submit（v4 多工种），需 X-Fe-Ai-Key + session_id；后四者另需 draft_id")
public class McpDraftController {

    private final McpDraftService mcpDraftService;

    public McpDraftController(McpDraftService mcpDraftService) {
        this.mcpDraftService = mcpDraftService;
    }

    @PostMapping("/generate")
    @Operation(summary = "生成初始草稿结构",
            description = "后端生成含 Schema 与 missing_fields 的草稿骨架，返回 draft_id。"
                    + "必填：worker_source、worker_count、work_days、work_type、work_location、settlement_mode、unit_amount"
                    + "（total_amount 非必填）。"
                    + "同会话已有 pending 草稿时幂等返回。",
            parameters = {
                    @Parameter(name = "X-Fe-Ai-Key", in = ParameterIn.HEADER,
                            description = "内网服务密钥")
            })
    public R<McpDraftGenerateResponse> generate(@Validated @RequestBody McpDraftGenerateRequest request) {
        return R.ok(mcpDraftService.generate(request.getSessionId(), request));
    }

    @PutMapping("/update")
    @Operation(summary = "更新草稿数据",
            description = "更新 worker_source、worker_groups（多工种）等字段；须传 draft_id；"
                    + "成功时返回 missing_fields；不可编辑时返回 status=ban。",
            parameters = {
                    @Parameter(name = "X-Fe-Ai-Key", in = ParameterIn.HEADER)
            })
    public R<McpDraftUpdateResponse> update(@Validated @RequestBody McpDraftUpdateRequest request) {
        return R.ok(mcpDraftService.update(request.getSessionId(), request));
    }

    @GetMapping("/info")
    @Operation(summary = "获取草稿详情与状态",
            description = "返回 status、data（含 worker_groups / total_worker_count 等）、"
                    + "editable、missing_fields。",
            parameters = {
                    @Parameter(name = "session_id", in = ParameterIn.QUERY, required = true,
                            description = "会话标识，与 AI chat session_id / conversation_no 一致"),
                    @Parameter(name = "draft_id", in = ParameterIn.QUERY, required = true,
                            description = "草稿 ID（generate 返回）"),
                    @Parameter(name = "X-Fe-Ai-Key", in = ParameterIn.HEADER)
            })
    public R<McpDraftInfoResponse> info(@RequestParam("session_id") String sessionId,
                                        @RequestParam("draft_id") Long draftId) {
        return R.ok(mcpDraftService.getInfo(sessionId, draftId));
    }

    @PostMapping("/calculate")
    @Operation(summary = "成本测算",
            description = "须传 draft_id；草稿就绪后测算。"
                    + "返回 draft_summary + schemes（含 group_breakdown 按工种拆分），并落库 fe_draft_cost_snapshot。",
            parameters = {
                    @Parameter(name = "X-Fe-Ai-Key", in = ParameterIn.HEADER)
            })
    public R<McpDraftCalculateResponse> calculate(@Validated @RequestBody McpDraftCalculateRequest request) {
        return R.ok(mcpDraftService.calculate(request.getSessionId(), request.getDraftId()));
    }

    @PostMapping("/submit")
    @Operation(summary = "确认并提交草稿",
            description = "须传 draft_id；用户选定方案后转化为正式订单，并创建登记批次、立刻生成小程序码。"
                    + "需先调用 calculate。",
            parameters = {
                    @Parameter(name = "X-Fe-Ai-Key", in = ParameterIn.HEADER)
            })
    public R<McpDraftSubmitResponse> submit(@Validated @RequestBody McpDraftSubmitRequest request) {
        return R.ok(mcpDraftService.submit(request.getSessionId(), request));
    }
}
