// ✅ 1. DYNAMICALLY RELOAD HELP CONTENT IN SPRING BOOT
// HelpService.java

import org.springframework.stereotype.Service;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.*;
import java.util.Map;

import com.contextual.help.HelpItem;
import java.nio.file.Path;


@Service
public class HelpService {
    private Map<String, HelpItem> helpData;
    private final Path helpPath = Paths.get("src/main/resources/help/help.en.json");
    private final ObjectMapper mapper = new ObjectMapper();

    @PostConstruct
    public void init() {
        loadHelp();
        watchForChanges();
    }

    private void loadHelp() {
        try (InputStream is = Files.newInputStream(helpPath)) {
            helpData = mapper.readValue(is, new TypeReference<>() {});
        } catch (IOException e) {
            throw new RuntimeException("Unable to load help data", e);
        }
    }

    private void watchForChanges() {
        new Thread(() -> {
            try (WatchService watcher = FileSystems.getDefault().newWatchService()) {
                helpPath.getParent().register(watcher, StandardWatchEventKinds.ENTRY_MODIFY);
                while (true) {
                    for (WatchEvent<?> event : watcher.take().pollEvents()) {
                        if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY
                                && event.context().toString().equals(helpPath.getFileName().toString())) {
                            System.out.println("Reloading help content...");
                            loadHelp();
                        }
                    }
                }
            } catch (IOException | InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }

    public Map<String, HelpItem> getAllHelp() {
        return helpData;
    }

    public HelpItem getHelp(String key) {
        return helpData.get(key);
    }
}

