package com.agileboot.codegen.controller;

import com.agileboot.codegen.dto.CodegenRequest;
import com.agileboot.codegen.dto.TemplatePreviewRequest;
import com.agileboot.codegen.service.IGeneratorService;
import com.agileboot.codegen.service.ITemplateRepositoryService;
import com.agileboot.codegen.service.ITemplateUsageLogService;
import com.agileboot.common.core.core.R;
import com.agileboot.common.satoken.utils.LoginHelper;
import com.agileboot.common.core.utils.ServletHolderUtil;
import com.alibaba.fastjson2.JSONArray;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author cuiJiaWang
 * @Create 2025-09-24 14:24
 */
@RestController
@RequestMapping("/codegen")
@Slf4j
@RequiredArgsConstructor
public class GeneratorController {

    private final IGeneratorService generatorService;
    private final ITemplateRepositoryService templateRepositoryService;
    private final ITemplateUsageLogService templateUsageLogService;

    @GetMapping("/template/all")
    public R<?> getAllTemplates() {
        try {
            Long userId = LoginHelper.getUserId();
            JSONArray templates = templateRepositoryService.getUserTemplateConfig(userId);
            return R.ok(templates);
        } catch (Exception e) {
            log.warn("获取用户模板配置失败，使用系统默认配置", e);
            // 降级到系统默认模板
            String templates = generatorService.getTemplateConfig();
            JSONArray jsonArray = JSONArray.parseArray(templates);
            return R.ok(jsonArray);
        }
    }

    @PostMapping("/code/generate")
    public R<?> generateCode(@RequestBody CodegenRequest request) {
        try {
            log.info("开始生成代码，表SQL: {}", request.getTableSql());

            // 合并请求参数
            Map<String, Object> options = new HashMap<>();
            if (request.getOptions() != null) {
                options.putAll(request.getOptions());
            }
            options.put("tableSql", request.getTableSql());

            // 获取用户的模板配置
            Long userId = LoginHelper.getUserId();
            JSONArray userTemplateConfig = templateRepositoryService.getUserTemplateConfig(userId);
            
            // 调用服务生成代码
            Map<String, String> result = generatorService.getResultByParams(options, userTemplateConfig.toJSONString());

            // 检查是否有错误
            if (result.containsKey("error")) {
                String errorMsg = result.get("error");
                log.warn("代码生成失败: {}", errorMsg);
                return R.fail(errorMsg);
            }

            // 记录模板使用日志
            try {
                String ipAddress = ServletHolderUtil.getClientIp();
                
                // 从请求参数中获取使用的模板信息
                if (options.containsKey("selectedTemplates")) {
                    @SuppressWarnings("unchecked")
                    Map<String, Object> selectedTemplates = (Map<String, Object>) options.get("selectedTemplates");
                    for (Map.Entry<String, Object> entry : selectedTemplates.entrySet()) {
                        String templateId = entry.getKey();
                        String templateName = entry.getValue().toString();
                        
                        // 判断模板来源
                        String templateSource = templateId.matches("\\d+") ? "system" : "user";
                        
                        templateUsageLogService.logTemplateUsage(userId, templateSource, templateId, 
                                templateName, "unknown", ipAddress);
                    }
                }
            } catch (Exception e) {
                log.warn("记录模板使用日志失败", e);
            }

            Map<String, Object> response = new HashMap<>();
            response.put("outputJson", result);
            response.put("tableName", result.get("tableName"));

            log.info("代码生成完成，表名: {}", result.get("tableName"));
            return R.ok(response);

        } catch (Exception e) {
            log.error("生成代码失败", e);
            return R.fail("生成代码失败: " + e.getMessage());
        }
    }

    @GetMapping("/template/content")
    public R<String> getTemplateContent(@RequestParam("templateSource") String templateSource,
                                       @RequestParam("templateId") String templateId) {
        try {
            String content = generatorService.getTemplateContentBySource(templateSource, templateId);
            return R.ok("获取成功", content);
        } catch (Exception e) {
            log.error("获取模板内容失败", e);
            return R.fail(e.getMessage());
        }
    }

    @GetMapping("/template/preview")
    public R<?> previewTemplateGet(@RequestParam("templateSource") String templateSource,
                                   @RequestParam("templateId") String templateId,
                                   @RequestParam(value = "tableSql", required = false) String tableSql,
                                   @RequestParam(value = "templateContent", required = false) String templateContent,
                                   @RequestParam(value = "authorName", required = false) String authorName) {
        try {
            log.info("开始预览模板(GET)，模板来源: {}, 模板ID: {}", templateSource, templateId);

            // 参数验证
            if (templateSource == null || templateId == null) {
                return R.fail("模板来源和模板ID不能为空");
            }

            // 如果没有提供tableSql，使用默认的示例SQL
            if (tableSql == null || tableSql.trim().isEmpty()) {
                tableSql = "CREATE TABLE `user` (\n" +
                          "  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',\n" +
                          "  `username` varchar(50) NOT NULL COMMENT '用户名',\n" +
                          "  `password` varchar(100) NOT NULL COMMENT '密码',\n" +
                          "  `email` varchar(100) DEFAULT NULL COMMENT '邮箱',\n" +
                          "  `phone` varchar(20) DEFAULT NULL COMMENT '手机号',\n" +
                          "  `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '状态(0-禁用 1-启用)',\n" +
                          "  `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',\n" +
                          "  `update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',\n" +
                          "  PRIMARY KEY (`id`),\n" +
                          "  UNIQUE KEY `uk_username` (`username`)\n" +
                          ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户表';";
                log.info("使用默认示例SQL进行模板预览");
            }

            // 构建选项参数
            Map<String, Object> options = new HashMap<>();
            options.put("tableSql", tableSql);
            if (authorName != null && !authorName.trim().isEmpty()) {
                options.put("authorName", authorName);
            }

            // 调用生成服务预览单个模板
            String previewResult = generatorService.previewSingleTemplate(
                    templateSource, 
                    templateId, 
                    templateContent,
                    options);

            log.info("模板预览完成(GET)，模板来源: {}, 模板ID: {}", templateSource, templateId);
            return R.ok("预览成功", previewResult);

        } catch (Exception e) {
            log.error("预览模板失败(GET)", e);
            return R.fail("预览模板失败: " + e.getMessage());
        }
    }

    @PostMapping("/template/preview")
    public R<?> previewTemplate(@RequestBody TemplatePreviewRequest request) {
        try {
            log.info("开始预览模板，模板来源: {}, 模板ID: {}", request.getTemplateSource(), request.getTemplateId());

            // 参数验证
            if (request.getTemplateSource() == null || request.getTemplateId() == null) {
                return R.fail("模板来源和模板ID不能为空");
            }

            if (request.getTableSql() == null || request.getTableSql().trim().isEmpty()) {
                return R.fail("表SQL语句不能为空");
            }

            // 合并请求参数
            Map<String, Object> options = new HashMap<>();
            if (request.getOptions() != null) {
                options.putAll(request.getOptions());
            }
            options.put("tableSql", request.getTableSql());

            // 调用生成服务预览单个模板
            String previewResult = generatorService.previewSingleTemplate(
                    request.getTemplateSource(), 
                    request.getTemplateId(), 
                    request.getTemplateContent(),
                    options);

            log.info("模板预览完成，模板来源: {}, 模板ID: {}", request.getTemplateSource(), request.getTemplateId());
            return R.ok("预览成功", previewResult);

        } catch (Exception e) {
            log.error("预览模板失败", e);
            return R.fail("预览模板失败: " + e.getMessage());
        }
    }
}
