import 'server-only';
import { getDailyUsage } from '@/lib/monitoring/costMonitor';

// ─────────────────────────────────────────────
// 경고 임계값
// ─────────────────────────────────────────────

export const ALERT_THRESHOLDS = {
    dailyCostUsd: 5.0,       // 일일 비용 $5 초과 시 경고
    hourlyQuerySpike: 3.0,   // 평균 대비 3배 이상 시 경고
    maxDailyQueries: 5000,   // 일일 최대 쿼리 수
};

// ─────────────────────────────────────────────
// 내부 헬퍼
// ─────────────────────────────────────────────

function getTodayDateString(): string {
    return new Date().toISOString().split('T')[0];
}

/**
 * hourlyQueryCounts에서 현재 시간(UTC)의 쿼리 수 반환
 */
function getCurrentHourlyRate(hourlyQueryCounts: Record<string, number>): number {
    const currentHour = new Date().getUTCHours().toString().padStart(2, '0');
    return hourlyQueryCounts[currentHour] ?? 0;
}

/**
 * hourlyQueryCounts 전체 평균 (기록된 시간대만 대상)
 */
function getAverageHourlyRate(hourlyQueryCounts: Record<string, number>): number {
    const values = Object.values(hourlyQueryCounts);
    if (values.length === 0) return 0;
    const total = values.reduce((sum, v) => sum + v, 0);
    return total / values.length;
}

// ─────────────────────────────────────────────
// Public API
// ─────────────────────────────────────────────

/**
 * 일일 비용 확인 및 경고
 * ALERT_THRESHOLDS.dailyCostUsd 초과 또는 일일 쿼리 한도 초과 시 isAlert=true
 */
export async function checkDailyCostAlert(date?: string): Promise<{
    isAlert: boolean;
    currentCost: number;
    threshold: number;
    message?: string;
}> {
    const targetDate = date ?? getTodayDateString();
    const usage = await getDailyUsage(targetDate);

    const currentCost = usage?.estimatedCostUsd ?? 0;
    const threshold = ALERT_THRESHOLDS.dailyCostUsd;
    const dailyQueries = usage?.queryCalls ?? 0;

    const isCostExceeded = currentCost > threshold;
    const isQueryLimitExceeded = dailyQueries > ALERT_THRESHOLDS.maxDailyQueries;
    const isAlert = isCostExceeded || isQueryLimitExceeded;

    if (!isAlert) {
        return { isAlert: false, currentCost, threshold };
    }

    const reasons: string[] = [];
    if (isCostExceeded) {
        reasons.push(
            `일일 비용 임계값 초과: $${currentCost.toFixed(4)} > $${threshold.toFixed(2)}`
        );
    }
    if (isQueryLimitExceeded) {
        reasons.push(
            `일일 쿼리 한도 초과: ${dailyQueries} > ${ALERT_THRESHOLDS.maxDailyQueries}`
        );
    }

    const message = `[COST ALERT] ${targetDate} — ${reasons.join(' / ')}`;
    console.warn(message);

    return { isAlert: true, currentCost, threshold, message };
}

/**
 * 트래픽 이상 감지
 * 현재 시간의 쿼리 수가 평균 대비 ALERT_THRESHOLDS.hourlyQuerySpike 배 이상이면 이상으로 판단
 */
export async function detectAnomalousTraffic(date?: string): Promise<{
    isAnomaly: boolean;
    currentHourlyRate: number;
    averageHourlyRate: number;
    spikeFactor: number;
    message?: string;
}> {
    const targetDate = date ?? getTodayDateString();
    const usage = await getDailyUsage(targetDate);

    const hourlyQueryCounts = usage?.hourlyQueryCounts ?? {};
    const currentHourlyRate = getCurrentHourlyRate(hourlyQueryCounts);
    const averageHourlyRate = getAverageHourlyRate(hourlyQueryCounts);

    // 평균이 0이면 분모가 0이 되므로 비율 계산 불가 → 이상 없음으로 처리
    const spikeFactor =
        averageHourlyRate > 0 ? currentHourlyRate / averageHourlyRate : 0;

    const isAnomaly = spikeFactor >= ALERT_THRESHOLDS.hourlyQuerySpike;

    if (!isAnomaly) {
        return {
            isAnomaly: false,
            currentHourlyRate,
            averageHourlyRate,
            spikeFactor,
        };
    }

    const message =
        `[TRAFFIC ANOMALY] ${targetDate} — ` +
        `현재 시간당 쿼리 수 ${currentHourlyRate}회 ` +
        `(평균 ${averageHourlyRate.toFixed(1)}회 대비 ${spikeFactor.toFixed(2)}배 급증)`;
    console.warn(message);

    return {
        isAnomaly: true,
        currentHourlyRate,
        averageHourlyRate,
        spikeFactor,
        message,
    };
}
