/*
 * Copyright (c) 2025 Rostock University Library
 * Licensed under the MIT License. See LICENSE file in the project root.
 */
package de.uni.rostock.ub.wsrb.edition.webapp.service;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.Map;

import javax.xml.transform.stream.StreamSource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Service;

import de.uni.rostock.ub.wsrb.edition.webapp.util.WSRBUtil;
import jakarta.annotation.PostConstruct;
import net.sf.saxon.s9api.Processor;
import net.sf.saxon.s9api.QName;
import net.sf.saxon.s9api.SaxonApiException;
import net.sf.saxon.s9api.XdmAtomicValue;
import net.sf.saxon.s9api.XdmMap;
import net.sf.saxon.s9api.XdmValue;
import net.sf.saxon.s9api.Xslt30Transformer;
import net.sf.saxon.s9api.XsltCompiler;
import net.sf.saxon.s9api.XsltExecutable;

@Service
public class XSLTTranskriptionService {

    private static final Logger LOGGER = LoggerFactory.getLogger(XSLTTranskriptionService.class);

    @Autowired
    DataService dataService;

    @Value("${wsrb.folder.teixml}")
    private String teixmlFolder;

    @Value("${wsrb.folder.xslt}")
    private String xsltFolder;

    XsltExecutable xslTranskription;
    Processor processor = new Processor(false);

    @PostConstruct
    private void init() {
        try (InputStream instrXsltTranskription
            = getClass().getResourceAsStream(xsltFolder + "transkriptionen/html4transkription.xsl")) {

            XsltCompiler compiler = processor.newXsltCompiler();
            xslTranskription = compiler.compile(new StreamSource(instrXsltTranskription));
        } catch (SaxonApiException | IOException e) {
            LOGGER.error("Initialisation exception:", e);
        }
    }

    public String createTranskription(@NonNull String id, @NonNull String te, @NonNull String anchor) {
        StringWriter sw = new StringWriter();
        String path = teixmlFolder + "transkriptionen/" + id + WSRBUtil.TEI_FILE_EXTENSION;
        try (InputStream instrTranskriptionXml = getClass().getResourceAsStream(path)) {
            Xslt30Transformer transformer = xslTranskription.load30();
            Map<QName, XdmValue> params = Map.ofEntries(
                Map.entry(new QName("tr_id"), new XdmAtomicValue(id)),
                Map.entry(new QName("anchor"), new XdmAtomicValue(anchor)),
                Map.entry(new QName("te"), new XdmAtomicValue(StringUtils.normalizeSpace(te.replace(",", " ")))),
                Map.entry(new QName("map_id2line"), XdmMap.makeMap(dataService.retrieveIdToLineMap())));

            transformer.setStylesheetParameters(params);
            transformer.transform(new StreamSource(instrTranskriptionXml), WSRBUtil.createSerializer(processor, sw));
        } catch (Exception e) {
            LOGGER.error("Could not create transcription:", e);
        }
        return sw.toString();
    }
}
