package gc.mda.signal_batch.batch.reader;

import jakarta.annotation.PostConstruct;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 중국 허가선박(ChnPrmShip) 설정
 *
 * 대상 MMSI 목록을 리소스 파일에서 로딩하여 Set으로 보관한다.
 * MMSI는 String 타입 — 문자 혼합 장비 지원
 */
@Slf4j
@Getter
@Setter
@Component
@ConfigurationProperties(prefix = "app.chnprmship")
public class ChnPrmShipProperties {

    private String mmsiResourcePath = "classpath:chnprmship-mmsi.txt";
    private int ttlDays = 2;
    private int maxSize = 2000;
    private boolean warmupEnabled = true;
    private int warmupDays = 2;

    private Set<String> mmsiSet = Collections.emptySet();

    @PostConstruct
    public void init() {
        try {
            Resource resource = new DefaultResourceLoader().getResource(mmsiResourcePath);
            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8))) {
                mmsiSet = reader.lines()
                        .map(String::trim)
                        .filter(line -> !line.isEmpty() && !line.startsWith("#"))
                        .collect(Collectors.toUnmodifiableSet());
            }
            log.info("ChnPrmShip MMSI 로딩 완료 - {}건 (경로: {})", mmsiSet.size(), mmsiResourcePath);
        } catch (Exception e) {
            log.warn("ChnPrmShip MMSI 로딩 실패 - 경로: {}, 오류: {} (비활성화됨)", mmsiResourcePath, e.getMessage());
            mmsiSet = Collections.emptySet();
        }
    }

    public boolean isTarget(String mmsi) {
        return mmsi != null && mmsiSet.contains(mmsi);
    }
}
