import Foundation

/// Represents a detected chess move
struct DetectedMove {
    /// The source square where the piece moved from
    let from: BoardPosition
    
    /// The target square where the piece moved to
    let to: BoardPosition
    
    /// The piece that was moved
    let piece: ChessPiece
}

/// A class responsible for detecting moves from highlighted squares
final class MoveDetector {
    /// Detect a move from a set of square classifications
    /// - Parameter squares: Dictionary mapping board positions to their classifications
    /// - Returns: Detected move if one is found, nil otherwise
    func detectMove(from squares: [BoardPosition: SquareClassification]) -> DetectedMove? {
        var sourceSquare: BoardPosition?
        var targetSquare: BoardPosition?
        var movedPiece: ChessPiece?
        
        // Find highlighted squares
        for (position, classification) in squares {
            guard classification.isHighlighted else { continue }
            
            if classification.isEmpty {
                // Empty highlighted square is the source
                sourceSquare = position
            } else if let color = classification.pieceColor,
                      let type = classification.pieceType {
                // Piece on highlighted square is the target
                targetSquare = position
                movedPiece = ChessPiece(type: type, color: color)
            }
        }
        
        // Return move if we found both squares and the piece
        if let from = sourceSquare,
           let to = targetSquare,
           let piece = movedPiece {
            return DetectedMove(from: from, to: to, piece: piece)
        }
        
        return nil
    }
}
