package me.qwq.doghouse;

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

import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import jodd.io.FileUtil;
import lombok.extern.slf4j.Slf4j;
import me.qwq.doghouse.config.DoghouseProperties;
import me.qwq.doghouse.entity.Asset;
import me.qwq.doghouse.entity.Post;
import me.qwq.doghouse.enums.FileTypeEnum;
import me.qwq.doghouse.enums.PostTypeEnum;
import me.qwq.doghouse.service.AssetService;
import me.qwq.doghouse.service.post.PostService;

@SpringBootTest
@Slf4j
public class ExportPost {

    @Autowired
    AssetService assetService;
    
    @Autowired
    PostService postService;
    
    @Autowired
    DoghouseProperties doghouseProperties;
    
    @Test
    void test() throws IOException {
        
        // 取出所有指定的 Post
        List<Post> posts = postService.list(new LambdaQueryWrapper<Post>()
                .eq(Post::getType, PostTypeEnum.WIKI));
        
        List<Asset> assets = assetService.list(
                new LambdaQueryWrapper<Asset>()
                .eq(Asset::getFileType, FileTypeEnum.IMAGE));

        File dir = new File("/wiki-backup");
        File imgDir = new File("/wiki-backup/imgs");

        if (!FileUtil.isExistingFolder(dir)) {
            FileUtil.mkdir(dir);
        }
        if (!FileUtil.isExistingFolder(imgDir)) {
            FileUtil.mkdir(imgDir);
        }
        
        // 查询其中所有图片
        for(Post post : posts) {
            String content = post.getPostContent();
            if (StringUtils.isEmpty(content)) continue;
            
            for (Asset asset : assets) {
                String realPath = doghouseProperties.getFileUploadPath(asset);
                String originalPath = asset.getPath();
                File assetFile = new File(realPath);
                File destFile = new File("/wiki-backup/imgs/" + assetFile.getName());
                if (content.contains(originalPath)) {
                    // 文件存在的，复制到路径
                    FileUtil.copy(assetFile, destFile);
                    content = content.replace(originalPath, "./imgs/" + assetFile.getName());
                }
            }
            // 在路径写 md
            File mdFile = new File("/wiki-backup/" + sanitizeFileName(post.getPostTitle()) + ".md");
            FileUtil.writeString(mdFile, content);
        };
        
    }
    
    public static String sanitizeFileName(String name) {
        if (name == null || name.isEmpty()) {
            return "_";
        }

        // 1. 替换核心非法字符为全角
        String sanitized = name
                .replace("/", "／")
                .replace("\\", "＼")
                .replace(":", "：")
                .replace("*", "＊")
                .replace("?", "？")
                .replace("\"", "＂")
                .replace("<", "＜")
                .replace(">", "＞")
                .replace("|", "｜");

        // 2. 去除前后空格（Windows 不允许）
        sanitized = sanitized.trim();

        // 3. 避免出现空结果
        if (sanitized.isEmpty()) {
            sanitized = "_";
        }

        // 4. Windows 保留字处理
        String upper = sanitized.toUpperCase();
        String[] reserved = {
                "CON", "PRN", "AUX", "NUL",
                "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9",
                "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9"
        };

        for (String r : reserved) {
            if (upper.equals(r)) {
                sanitized = sanitized + "_";
                break;
            }
        }

        return sanitized;
    }
}
