package com.erp.ai.service;

import com.erp.ai.dto.UsageSummaryResponse;
import com.erp.ai.mapper.AiAgentApiKeyMapper;
import com.erp.ai.mapper.AiAgentMapper;
import com.erp.ai.mapper.AiAgentUsageLogMapper;
import com.erp.ai.model.AiAgentUsageLog;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * AI 사용량/비용 집계 서비스.
 * vexplor aiAgentUsageService.ts 1:1 포팅.
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AiAgentUsageService {

    private final AiAgentUsageLogMapper usageMapper;
    private final AiAgentMapper agentMapper;
    private final AiAgentApiKeyMapper apiKeyMapper;

    public void log(AiAgentUsageLog data) {
        if (data.getSuccess() == null) data.setSuccess(true);
        usageMapper.insert(data);
    }

    public UsageSummaryResponse getSummary() {
        Map<String, Object> today = usageMapper.getTodayAggregate();
        Map<String, Object> month = usageMapper.getMonthAggregate();
        int activeAgents = agentMapper.countActive();
        int activeKeys = apiKeyMapper.countActive();

        return UsageSummaryResponse.builder()
                .today_tokens(toLong(today.get("tokens")))
                .today_requests(toLong(today.get("requests")))
                .today_cost(toBigDecimal(today.get("cost")))
                .month_tokens(toLong(month.get("tokens")))
                .month_requests(toLong(month.get("requests")))
                .month_cost(toBigDecimal(month.get("cost")))
                .active_agents(activeAgents)
                .active_keys(activeKeys)
                .build();
    }

    public Map<String, Object> getLogs(int page, int limit) {
        int offset = (page - 1) * limit;
        List<AiAgentUsageLog> logs = usageMapper.list(limit, offset);
        int total = usageMapper.count();
        Map<String, Object> result = new HashMap<>();
        result.put("logs", logs);
        result.put("total", total);
        return result;
    }

    public List<Map<String, Object>> getDailyUsage(int days) {
        return usageMapper.getDailyUsage(days);
    }

    public long getMonthTokensByApiKey(long apiKeyId) {
        return usageMapper.getMonthTokensByApiKey(apiKeyId);
    }

    private long toLong(Object v) {
        if (v == null) return 0L;
        if (v instanceof Number n) return n.longValue();
        return Long.parseLong(v.toString());
    }

    private BigDecimal toBigDecimal(Object v) {
        if (v == null) return BigDecimal.ZERO;
        if (v instanceof BigDecimal b) return b;
        if (v instanceof Number n) return BigDecimal.valueOf(n.doubleValue());
        return new BigDecimal(v.toString());
    }
}
