import Foundation
import UIKit
import CoreImage

/// Manages undo/redo history for the image editor
public class HistoryManager {
    private var undoStack: [EditorState] = []
    private var redoStack: [EditorState] = []
    private(set) public var maxHistoryStates: Int

    public var canUndo: Bool {
        return !undoStack.isEmpty
    }

    public var canRedo: Bool {
        return !redoStack.isEmpty
    }

    public init(maxHistoryStates: Int = 50) {
        self.maxHistoryStates = maxHistoryStates
    }

    /// Update maximum history depth (useful for adaptive memory management)
    public func updateMaxHistoryStates(_ newMax: Int) {
        self.maxHistoryStates = max(1, newMax)

        // Trim if necessary
        if undoStack.count > maxHistoryStates {
            let removeCount = undoStack.count - maxHistoryStates
            undoStack.removeFirst(removeCount)
        }
    }

    /// Saves the current state
    public func saveState(_ state: EditorState) {
        undoStack.append(state)
        redoStack.removeAll()

        // Limit history size
        if undoStack.count > maxHistoryStates {
            undoStack.removeFirst()
        }
    }

    /// Undoes the last operation
    public func undo(currentState: EditorState) -> EditorState? {
        guard canUndo else { return nil }

        redoStack.append(currentState)
        return undoStack.removeLast()
    }

    /// Redoes the last undone operation
    public func redo(currentState: EditorState) -> EditorState? {
        guard canRedo else { return nil }

        undoStack.append(currentState)
        return redoStack.removeLast()
    }

    /// Clears all history
    public func clear() {
        undoStack.removeAll()
        redoStack.removeAll()
    }
}

/// Represents a snapshot of the editor state
public struct EditorState {
    public let layers: [ImageLayer]
    public let adjustments: [String: Any]
    public let timestamp: Date

    public init(layers: [ImageLayer], adjustments: [String: Any], timestamp: Date = Date()) {
        self.layers = layers
        self.adjustments = adjustments
        self.timestamp = timestamp
    }
}
