package com.ytpm.lemonios.config.ip2Regin;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import org.lionsoul.ip2region.service.Config;
import org.lionsoul.ip2region.service.Ip2Region;
import org.lionsoul.ip2region.xdb.Searcher;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * @author lih
 * @date 2025-12-25 14:52
 */
@Configuration
public class IPReginConfig {

    @Value("${ip2-regin.v4.fileName:ip2region_v4.xdb}")
    private String ip2RegionV4FileName;

    @Value("${ip2-regin.v6.filename:ip2region_v6.xdb}")
    private String ip2regionV6FileName;

    @Bean
    public Ip2Region ip2Regin() throws Exception {
        File ip2RegionV4 = getRegionFile(ip2RegionV4FileName);
        File ip2RegionV6 = getRegionFile(ip2regionV6FileName);
        try {
            Searcher.verifyFromFile(ip2RegionV4);
        } catch (Exception e) {
            throw new RuntimeException(StrUtil.format("文件不可用:{}", ip2RegionV4FileName));
        }
        try {
            Searcher.verifyFromFile(ip2RegionV6);
        } catch (Exception e) {
            throw new RuntimeException(StrUtil.format("文件不可用:{}", ip2regionV6FileName));
        }
        Config v4Config = Config.custom()
                .setCachePolicy(Config.VIndexCache)     // 指定缓存策略:  NoCache / VIndexCache / BufferCache
                .setSearchers(15)                       // 设置初始化的查询器数量
                .setXdbFile(ip2RegionV4)
                .asV4();

        Config v6Config = Config.custom()
                .setCachePolicy(Config.VIndexCache)     // 指定缓存策略: NoCache / VIndexCache / BufferCache
                .setSearchers(15)                       // 设置初始化的查询器数量
                .setXdbFile(ip2RegionV6)    // 设置 v6 xdb 文件的路径
                .asV6();
        return Ip2Region.create(v4Config, v6Config);
    }

    private File getRegionFile(String fileName) throws FileNotFoundException {
        String externalFilePath = Paths.get(System.getProperty("user.dir"), fileName).toString();
        File externalFile = new File(externalFilePath);
        if (externalFile.exists() && externalFile.isFile()) {
            return externalFile;
        }
        // 2. 同级目录不存在，查找classpath资源（支持JAR包内部）
        ClassPathResource internalResource = new ClassPathResource(fileName);
        if (internalResource.exists()) {
            try (InputStream inputStream = internalResource.getInputStream()) {
                // 创建临时文件（前缀为文件名，后缀自动生成，默认存储在系统临时目录）
                File tempFile = File.createTempFile(StrUtil.removeSuffix(fileName, "." + FileUtil.extName(fileName)),
                        "." + FileUtil.extName(fileName));
                // 将JAR内资源字节流写入临时文件
                Files.copy(inputStream, tempFile.toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING);
                // 可选：设置临时文件在JVM退出时自动删除
                tempFile.deleteOnExit();
                return tempFile;
            } catch (IOException e) {
                throw new RuntimeException(StrUtil.format("JAR内资源转临时文件失败:{}", fileName), e);
            }
        }

        // 3. 两者均不存在，抛出异常
        throw new FileNotFoundException(StrUtil.format("文件/资源不存在:{}", fileName));
    }


}
