import Foundation
import UIKit
import CoreImage
import Metal

/// Configuration for the ImageEditor engine
public struct ImageEditorConfig {
    /// Maximum texture size for Metal processing
    public var maxTextureSize: Int = 4096

    /// Enable GPU acceleration via Metal
    public var useMetalAcceleration: Bool = true

    /// Processing quality level
    public var processingQuality: ProcessingQuality = .high

    /// Maximum history states to keep
    public var maxHistoryStates: Int = 50

    /// Cache filter results
    public var cacheFilterResults: Bool = true

    public init() {}

    public enum ProcessingQuality {
        case low
        case medium
        case high
        case ultra

        var ciContextOptions: [CIContextOption: Any] {
            switch self {
            case .low:
                return [.workingColorSpace: NSNull()]
            case .medium:
                return [.workingColorSpace: CGColorSpaceCreateDeviceRGB()]
            case .high, .ultra:
                return [
                    .workingColorSpace: CGColorSpaceCreateDeviceRGB(),
                    .highQualityDownsample: true
                ]
            }
        }
    }
}

/// Result of an editing operation
public enum ImageEditorResult {
    case success(UIImage)
    case failure(ImageEditorError)
}

/// Errors that can occur during image editing
public enum ImageEditorError: Error, LocalizedError {
    case imageLoadFailed
    case invalidParameters
    case processingFailed
    case exportFailed
    case metalNotAvailable
    case outOfMemory
    case invalidLayerIndex
    case filterNotFound

    public var errorDescription: String? {
        switch self {
        case .imageLoadFailed:
            return "Failed to load image"
        case .invalidParameters:
            return "Invalid parameters provided"
        case .processingFailed:
            return "Image processing failed"
        case .exportFailed:
            return "Failed to export image"
        case .metalNotAvailable:
            return "Metal GPU acceleration not available"
        case .outOfMemory:
            return "Out of memory"
        case .invalidLayerIndex:
            return "Invalid layer index"
        case .filterNotFound:
            return "Filter not found"
        }
    }
}
