using System;
using System.IO;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.Rendering;

public static class URPBaselineCaptureTool {
    private const string OutputDirectory = "Temp/urp-baselines";

    [MenuItem("Eagle0/Rendering/Capture URP Baseline Screenshot")]
    public static void CaptureBaselineScreenshot() {
        var projectRoot = Path.GetFullPath(Path.Combine(Application.dataPath, ".."));
        var outputDirectory = Path.Combine(projectRoot, OutputDirectory);
        Directory.CreateDirectory(outputDirectory);

        var sceneName = EditorSceneManager.GetActiveScene().name;
        if (string.IsNullOrWhiteSpace(sceneName)) { sceneName = "unsaved-scene"; }

        var fileName =
                $"{ActiveRenderPipelinePrefix()}_{DateTime.Now:yyyyMMdd_HHmmss}_{SanitizeFileName(sceneName)}.png";
        var outputPath = Path.Combine(outputDirectory, fileName);

        ScreenCapture.CaptureScreenshot(outputPath);
        Debug.Log($"URP baseline screenshot requested: {outputPath}");
    }

    private static string SanitizeFileName(string value) {
        var invalidChars = Path.GetInvalidFileNameChars();
        foreach (var invalidChar in invalidChars) { value = value.Replace(invalidChar, '-'); }
        return value.Replace(' ', '-').ToLowerInvariant();
    }

    private static string ActiveRenderPipelinePrefix() {
        var qualityPipeline =
                QualitySettings.GetRenderPipelineAssetAt(QualitySettings.GetQualityLevel());
        var pipeline =
                qualityPipeline != null ? qualityPipeline : GraphicsSettings.defaultRenderPipeline;
        return pipeline == null ? "birp" : "urp";
    }
}
