package com.psg.dlsysinfo.dl_sysinfo_server.scheduling;

import com.psg.dlsysinfo.dl_sysinfo_server.service.CveStatisticsService;
import com.psg.dlsysinfo.dl_sysinfo_server.service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.Map;

@Component
public class CveSyncScheduler {

    private final File logFile = new File("cve-sync.log");

    @Autowired
    private EmailService emailService;

    @Autowired
    private CveStatisticsService cveStatisticsService;


    @Scheduled(cron = "0 0 */8 * * *") // ⏰ Every 8 hours
    public void runCveSyncScript() {
        File scriptFile = new File("scripts/fetchCVE.js");

        if (!scriptFile.exists()) {
            String msg = "❌ Script not found: " + scriptFile.getAbsolutePath();
            log(msg);
            emailService.sendHtmlEmail("⚠️ CVE Sync Failed", wrapHtml(msg));
            return;
        }

        try {
            ProcessBuilder pb = new ProcessBuilder("node", scriptFile.getAbsolutePath());
            Map<String, String> env = pb.environment();
            env.put("DB_HOST", System.getenv("DB_HOST"));
            env.put("DB_USER", System.getenv("DB_USER"));
            env.put("DB_PASSWORD", System.getenv("DB_PASSWORD"));
            env.put("DB_NAME", System.getenv("DB_NAME"));
            env.put("NVD_API_KEY", System.getenv("NVD_API_KEY"));
            env.put("NVD_MAX_RANGE_DAYS", System.getenv("NVD_MAX_RANGE_DAYS"));

            pb.redirectErrorStream(true);
            Process process = pb.start();

            StringBuilder output = new StringBuilder();
            output.append("=== CVE Sync Run at ").append(LocalDateTime.now()).append(" ===\n");

            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8));
                 FileWriter fw = new FileWriter(logFile, true)) {

                String line;
                while ((line = reader.readLine()) != null) {
                    output.append(line).append("\n");
                    fw.write(line + "\n");
                }

                int exitCode = process.waitFor();
                output.append(">>> Exit Code: ").append(exitCode).append("\n");
                fw.write(">>> Exit Code: " + exitCode + "\n");

                String subject = (exitCode == 0 ? "✅ CVE Sync Complete" : "⚠️ CVE Sync Completed with Errors");
                emailService.sendHtmlEmail(subject, wrapHtml(output.toString()));
                if (exitCode == 0) {
                    cveStatisticsService.refreshStatistics();
                }

            }

        } catch (Exception e) {
            String err = "❌ Exception during CVE sync: " + e.getMessage();
            log(err);
            emailService.sendHtmlEmail("❌ CVE Sync Error", wrapHtml(err));
        }
    }

    private void log(String message) {
        try (FileWriter fw = new FileWriter(logFile, true)) {
            fw.write(LocalDateTime.now() + " — " + message + "\n");
        } catch (IOException ignored) {}
    }

    private String wrapHtml(String content) {
        return """
            <html>
              <body style="font-family: sans-serif; font-size: 14px;">
                <h2 style="color: #2E86C1;">CVE Sync Report</h2>
                <pre style="background: #f4f4f4; padding: 1em; border-radius: 4px;">%s</pre>
              </body>
            </html>
            """.formatted(content.replace("<", "&lt;").replace(">", "&gt;"));
    }
}
