package com.erp.ai.health;

import com.erp.ai.client.OpenClawClient;
import com.erp.ai.config.OpenClawProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * OpenClaw 헬스 상태를 주기적으로 갱신하는 컴포넌트.
 * Spring Boot Actuator 미설치 환경을 고려해 독립 구현.
 * Actuator 도입 시 HealthIndicator 구현으로 전환 가능.
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class OpenClawHealthIndicator {

    private final OpenClawClient openClawClient;
    private final OpenClawProperties props;

    private final AtomicBoolean healthy = new AtomicBoolean(false);

    /**
     * 설정된 health-check-interval 마다 헬스 상태 갱신.
     * fixedRateString 은 application.yml openclaw.health-check-interval(ms 단위 Duration) 사용.
     */
    @Scheduled(fixedRateString = "#{@openClawProperties.healthCheckInterval.toMillis()}")
    public void checkHealth() {
        if (!props.isEnabled()) {
            healthy.set(false);
            return;
        }
        boolean result = openClawClient.isHealthy();
        if (healthy.get() != result) {
            log.info("OpenClaw health changed: {}", result ? "UP" : "DOWN");
        }
        healthy.set(result);
    }

    /**
     * 현재 캐시된 헬스 상태 반환.
     */
    public boolean isHealthy() {
        return healthy.get();
    }
}
