package com.lesingle.edu.dto.response;

import com.alibaba.fastjson2.JSON;
import com.lesingle.edu.entity.CoursePackage;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Builder;
import lombok.Data;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 学校端课程响应（gradeTags/domainTags 规范为 String[]，与套餐管理适用年级对齐）
 */
@Data
@Builder
@Schema(description = "学校端课程响应")
public class SchoolCourseResponse {

    @Schema(description = "ID")
    private Long id;

    @Schema(description = "租户 ID")
    private Long tenantId;

    @Schema(description = "课程名称")
    private String name;

    @Schema(description = "课程编码")
    private String code;

    @Schema(description = "描述")
    private String description;

    @Schema(description = "绘本名称")
    private String pictureBookName;

    @Schema(description = "封面图片路径")
    private String coverImagePath;

    @Schema(description = "封面 URL")
    private String coverUrl;

    @Schema(description = "年级标签（规范为数组）")
    private String[] gradeTags;

    @Schema(description = "领域标签（规范为数组）")
    private String[] domainTags;

    @Schema(description = "课程时长（分钟）")
    private Integer duration;

    @Schema(description = "使用次数")
    private Integer usageCount;

    @Schema(description = "教师数量")
    private Integer teacherCount;

    @Schema(description = "平均评分")
    private BigDecimal avgRating;

    @Schema(description = "状态")
    private String status;

    @Schema(description = "创建时间")
    private LocalDateTime createdAt;

    @Schema(description = "更新时间")
    private LocalDateTime updatedAt;

    @Schema(description = "课程环节标签（列表展示用，仅 name 和 lessonType）")
    private List<LessonTagResponse> lessonTags;

    /**
     * 转换为学校端课程响应（gradeTags/domainTags 规范为 String[]）
     */
    public static SchoolCourseResponse toSchoolCourseResponse(CoursePackage pkg) {
        return SchoolCourseResponse.builder()
                .id(pkg.getId())
                .tenantId(pkg.getTenantId())
                .name(pkg.getName())
                .code(pkg.getCode())
                .description(pkg.getDescription())
                .pictureBookName(pkg.getPictureBookName())
                .coverImagePath(pkg.getCoverImagePath())
                .coverUrl(pkg.getCoverUrl())
                .gradeTags(parseJsonArray(pkg.getGradeTags()))
                .domainTags(parseJsonArray(pkg.getDomainTags()))
                .duration(pkg.getDurationMinutes())
                .usageCount(pkg.getUsageCount())
                .teacherCount(pkg.getTeacherCount())
                .avgRating(pkg.getAvgRating())
                .status(pkg.getStatus())
                .createdAt(pkg.getCreatedAt())
                .updatedAt(pkg.getUpdatedAt())
                .build();
    }

    /**
     * 解析 JSON 数组为 String[]，兼容多种格式：
     * - 标准 JSON: ["小班","中班"]
     * - 逗号分隔: 小班,中班
     * - 错误格式（split 导致）: ["[\"小班\"", " \"中班\""] -> 提取有效值
     */
    private static String[] parseJsonArray(String json) {
        if (!StringUtils.hasText(json)) {
            return new String[0];
        }
        String s = json.trim();
        try {
            if (s.startsWith("[")) {
                var list = JSON.parseArray(s, String.class);
                if (list != null && !list.isEmpty()) {
                    // 检查是否为被错误 split 的格式，如 ["[\"小班\"", " \"中班\""]
                    String first = list.get(0);
                    if (first != null && first.startsWith("[\"") && !first.contains(",")) {
                        return list.stream()
                                .map(String::trim)
                                .map(SchoolCourseResponse::extractQuotedValue)
                                .filter(v -> v != null && !v.isEmpty())
                                .toArray(String[]::new);
                    }
                    return list.stream()
                            .map(v -> v != null ? v.trim() : "")
                            .filter(v -> !v.isEmpty())
                            .toArray(String[]::new);
                }
                return new String[0];
            }
            return java.util.Arrays.stream(s.split(","))
                    .map(String::trim)
                    .filter(v -> !v.isEmpty())
                    .toArray(String[]::new);
        } catch (Exception e) {
            return new String[0];
        }
    }

    private static String extractQuotedValue(String s) {
        if (s == null) return null;
        s = s.trim();
        int start = s.indexOf('"');
        if (start >= 0) {
            int end = s.indexOf('"', start + 1);
            if (end > start) {
                return s.substring(start + 1, end).trim();
            }
        }
        return s.replaceAll("^\\[\"|\"\\]?$", "").trim();
    }
}
