package com.saas.voip.service;

import jakarta.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;




@Service
@Slf4j
public class EmmaPromptService {

    @Value("${emma.prompts.fallback}")
    private String fallbackPromptFromConfig;
    
    private String fullSystemPrompt;

    @PostConstruct
    public void init() {
        try {
            LocalDateTime now = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

            
            log.info("📚 [Emma] Loading system prompt and RAG knowledge base... : ", now.format(formatter));
            
            String systemPrompt = loadPromptFile("prompts/emma_system.md");
            String ragKnowledge = loadPromptFile("prompts/emma_rag.md");
            
           /* this.fullSystemPrompt = systemPrompt + "\n\n" + 
                                   "**=== DATE ET HEURE ===**\n\n" +
                                   now.format(formatter) + "\n\n" +
                                   "**=== BASE DE CONNAISSANCES (RAG) ===**\n\n" +
                                   ragKnowledge;
            */
            
            this.fullSystemPrompt = systemPrompt + "\n\n" + 
                   "**=== DATE ET HEURE ===**\n\n" +
                   now.format(formatter);
            
            log.info("✅ [Emma] System prompt loaded successfully ({} characters)", fullSystemPrompt.length());
            log.info("📊 [Emma] Estimated tokens: ~{}", fullSystemPrompt.length() / 4);
            
        } catch (IOException e) {
            log.error("❌ [Emma] Failed to load prompt files", e);
            this.fullSystemPrompt = getFallbackPrompt();
        }
    }

    public String getFullSystemPrompt() {
        return fullSystemPrompt;
    }

    private String loadPromptFile(String resourcePath) throws IOException {
        ClassPathResource resource = new ClassPathResource(resourcePath);
        try (InputStream inputStream = resource.getInputStream()) {
            byte[] bytes = FileCopyUtils.copyToByteArray(inputStream);
            return new String(bytes, StandardCharsets.UTF_8);
        }
    }

    private String getFallbackPrompt() {
        log.warn("⚠️ [Emma] Using fallback prompt from configuration due to file loading error");
        return fallbackPromptFromConfig;
    }
}
