package com.clanstop.healing.hooks;

import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.concurrent.atomic.AtomicLong;

/** Saves a PNG of the current page to disk. Best-effort: returns null (with a warning) on any error. */
public final class Screenshots {

    private static final Logger log = LoggerFactory.getLogger(Screenshots.class);
    private static final AtomicLong SEQ = new AtomicLong();

    private Screenshots() {}

    /** @return the saved file path, or null if the driver can't screenshot or the write fails. */
    public static String capture(WebDriver driver, String dir, String prefix) {
        if (!(driver instanceof TakesScreenshot shooter)) {
            return null;
        }
        try {
            File src = shooter.getScreenshotAs(OutputType.FILE);
            Path outDir = Path.of(dir);
            Files.createDirectories(outDir);
            String name = sanitize(prefix) + "-" + SEQ.incrementAndGet() + ".png";
            Path dest = outDir.resolve(name);
            Files.copy(src.toPath(), dest, StandardCopyOption.REPLACE_EXISTING);
            return dest.toAbsolutePath().toString();
        } catch (Exception e) {
            log.warn("screenshot capture failed: {}", e.getMessage());
            return null;
        }
    }

    private static String sanitize(String s) {
        String cleaned = s == null ? "shot" : s.replaceAll("[^a-zA-Z0-9._-]+", "_");
        return cleaned.length() > 80 ? cleaned.substring(0, 80) : cleaned;
    }
}
