package com.smyhub.infogenie.infogeniebackendjava.service;

import com.smyhub.infogenie.infogeniebackendjava.dto.request.AdminAIRuntimeRequest;
import com.smyhub.infogenie.infogeniebackendjava.dto.response.AIRuntimeResponse;
import com.smyhub.infogenie.infogeniebackendjava.entity.SiteAIRuntime;
import com.smyhub.infogenie.infogeniebackendjava.repository.SiteAIRuntimeRepository;
import com.smyhub.infogenie.infogeniebackendjava.util.AiResponseUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 * Reads and updates the singleton SiteAIRuntime row (id=1).
 * Used by the AI service to resolve the active DeepSeek endpoint.
 */
@Service
@RequiredArgsConstructor
public class AIRuntimeService {

    private final SiteAIRuntimeRepository runtimeRepo;
    private final AiResponseUtil aiResponseUtil;

    public Optional<SiteAIRuntime> getRuntime() {
        return runtimeRepo.findById(1L);
    }

    public AIRuntimeResponse getRuntimeResponse() {
        SiteAIRuntime row = runtimeRepo.findById(1L).orElse(new SiteAIRuntime());
        AIRuntimeResponse resp = new AIRuntimeResponse();
        resp.setApiBase(row.getApiBase());
        resp.setApiKeyHint(aiResponseUtil.maskApiKey(row.getApiKey()));
        resp.setDefaultModel(row.getDefaultModel());
        resp.setDefaultProvider(row.getDefaultProvider());
        if (row.getUpdatedAt() != null) {
            resp.setUpdatedAt(row.getUpdatedAt().toString());
        }
        return resp;
    }

    @Transactional
    public AIRuntimeResponse updateRuntime(AdminAIRuntimeRequest req) {
        SiteAIRuntime row = runtimeRepo.findById(1L).orElse(new SiteAIRuntime());
        row.setId(1L);

        if (req.getApiBase() != null) {
            row.setApiBase(req.getApiBase());
        }
        if (!aiResponseUtil.isKeyPlaceholder(req.getApiKey())) {
            row.setApiKey(req.getApiKey());
        }
        if (req.getDefaultModel() != null) {
            row.setDefaultModel(req.getDefaultModel());
        }
        if (req.getDefaultProvider() != null) {
            row.setDefaultProvider(req.getDefaultProvider());
        }

        runtimeRepo.save(row);
        return getRuntimeResponse();
    }
}
