package de.avatic.lcc.service.help;

import org.commonmark.node.Node;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.html.HtmlRenderer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class MarkdownService {

    private static final Logger logger = LoggerFactory.getLogger(MarkdownService.class);

    @Value(value = "${lcc.help.static:}")
    private String imagesBaseUrl;

    @Value("${help.markdown.cache.enabled:true}")
    private boolean cacheEnabled;

    private final Parser parser;
    private final HtmlRenderer renderer;
    private final Map<String, String> contentCache = new ConcurrentHashMap<>();

    public MarkdownService() {

        this.parser = Parser.builder()

                .build();

        this.renderer = HtmlRenderer.builder()

                .escapeHtml(false)  // HTML in Markdown erlauben
                .sanitizeUrls(true) // URLs sanitizen
                .build();

    }

    /**
     * Konvertiert Markdown-String zu HTML
     */
    public String convertToHtml(String markdown, String imagePrefix) {
        if (markdown == null || markdown.isEmpty()) {
            return "";
        }

        Node document = parser.parse(markdown);
        String html = renderer.render(document);

        // Bild-URLs anpassen
        return replaceImageUrls(html, imagePrefix);
    }

    /**
     * Lädt Markdown-Datei und konvertiert zu HTML
     */
    public String loadAndConvertMarkdown(String fileName, String imagePrefix) throws IOException {
        // Cache-Key erstellen
        String cacheKey = fileName + "_" + imagesBaseUrl.hashCode();

        // Aus Cache laden wenn aktiviert
        if (cacheEnabled && contentCache.containsKey(cacheKey)) {
            logger.debug("Loading help content from cache: {}", fileName);
            return contentCache.get(cacheKey);
        }

        logger.debug("Loading help content from file: {}", fileName);

        // Markdown-Datei laden
        String markdown = loadMarkdownFile(fileName);

        // Zu HTML konvertieren
        String html = convertToHtml(markdown, imagePrefix);

        // In HTML-Template einbetten
//        html = wrapInHtmlTemplate(html, fileName);

        // Im Cache speichern
        if (cacheEnabled) {
            contentCache.put(cacheKey, html);
        }

        return html;
    }

    /**
     * Lädt Markdown-Datei aus Resources
     */
    private String loadMarkdownFile(String fileName) throws IOException {
        // .md Extension hinzufügen falls nicht vorhanden
        if (!fileName.endsWith(".md")) {
            fileName = fileName + ".md";
        }

        Resource resource = new ClassPathResource("static/help/" + fileName);

        if (!resource.exists()) {
            throw new IOException("Help file not found: " + fileName);
        }

        return new String(resource.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
    }

    /**
     * Ersetzt relative Bild-URLs durch absolute URLs zum Azure Blob Storage
     */
    private String replaceImageUrls(String html, String imagePrefix) {
        if (imagesBaseUrl == null || imagesBaseUrl.isEmpty()) {
            logger.warn("Images base URL not configured");
            return html;
        }

        // Verschiedene Bild-URL-Formate ersetzen
        html = html.replaceAll("src=\"images/", "src=\"" + imagesBaseUrl + "/" + imagePrefix + "-");
        html = html.replaceAll("src='images/", "src='" + imagesBaseUrl + "/" + imagePrefix + "-");
        html = html.replaceAll("src=\"./images/", "src=\"" + imagesBaseUrl + "/" + imagePrefix + "-");

        return html;
    }

    /**
     * Bettet HTML-Inhalt in vollständiges HTML-Dokument ein
     */
    private String wrapInHtmlTemplate(String content, String title) {
        return """
                <!DOCTYPE html>
                <html lang="de">
                <head>
                    <meta charset="UTF-8">
                    <meta name="viewport" content="width=device-width, initial-scale=1.0">
                    <title>%s</title>
                    <style>
                        body {
                            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
                            line-height: 1.6;
                            color: #333;
                            max-width: 900px;
                            margin: 0 auto;
                            padding: 20px;
                        }
                        img {
                            max-width: 100%%;
                            height: auto;
                            border-radius: 4px;
                            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
                            margin: 1rem 0;
                        }
                        h1 {
                            color: #2c3e50;
                            border-bottom: 2px solid #3498db;
                            padding-bottom: 0.5rem;
                        }
                        h2 {
                            color: #34495e;
                            margin-top: 2rem;
                        }
                        h3 {
                            color: #34495e;
                        }
                        table {
                            width: 100%%;
                            border-collapse: collapse;
                            margin: 1rem 0;
                        }
                        th, td {
                            padding: 12px;
                            text-align: left;
                            border: 1px solid #ddd;
                        }
                        th {
                            background-color: #3498db;
                            color: white;
                        }
                        tr:nth-child(even) {
                            background-color: #f2f2f2;
                        }
                        code {
                            background-color: #f4f4f4;
                            padding: 2px 6px;
                            border-radius: 3px;
                            font-family: 'Courier New', monospace;
                        }
                        pre {
                            background-color: #f4f4f4;
                            padding: 1rem;
                            border-radius: 4px;
                            overflow-x: auto;
                        }
                        blockquote {
                            border-left: 4px solid #3498db;
                            padding-left: 1rem;
                            margin-left: 0;
                            color: #666;
                        }
                        a {
                            color: #3498db;
                            text-decoration: none;
                        }
                        a:hover {
                            text-decoration: underline;
                        }
                        ul, ol {
                            padding-left: 2rem;
                        }
                        li {
                            margin: 0.5rem 0;
                        }
                    </style>
                </head>
                <body>
                    %s
                </body>
                </html>
                """.formatted(title, content);
    }

    /**
     * Leert den Content-Cache
     */
    public void clearCache() {
        contentCache.clear();
        logger.info("Help content cache cleared");
    }

    /**
     * Gibt Cache-Statistiken zurück
     */
    public Map<String, Object> getCacheStats() {
        return Map.of(
                "cacheEnabled", cacheEnabled,
                "cachedFiles", contentCache.size(),
                "imagesBaseUrl", imagesBaseUrl
        );
    }
}