import Foundation

/// A class responsible for generating FEN strings from square classifications
final class FenGenerator {
    /// Generate a FEN string from a set of square classifications
    /// - Parameter squares: Dictionary mapping board positions to their classifications
    /// - Returns: FEN string representing the position
    func generateFen(from squares: [BoardPosition: SquareClassification]) -> String {
        var fen = ""
        var emptyCount = 0
        
        // Process each rank from top to bottom (8 to 1)
        for rank in (0...7).reversed() {
            // Process each file from left to right (a to h)
            for file in 0...7 {
                let position = BoardPosition(file: file, rank: rank)
                guard let square = squares[position] else {
                    // If square is missing, treat as empty
                    emptyCount += 1
                    continue
                }
                
                if square.isEmpty {
                    // Count consecutive empty squares
                    emptyCount += 1
                } else if let color = square.pieceColor,
                          let type = square.pieceType {
                    // If we had empty squares before this piece, add the count
                    if emptyCount > 0 {
                        fen += String(emptyCount)
                        emptyCount = 0
                    }
                    
                    // Add the piece symbol
                    let symbol = pieceSymbol(color: color, type: type)
                    fen += symbol
                }
            }
            
            // Add any remaining empty squares at end of rank
            if emptyCount > 0 {
                fen += String(emptyCount)
                emptyCount = 0
            }
            
            // Add rank separator (except for last rank)
            if rank > 0 {
                fen += "/"
            }
        }
        
        return fen
    }
    
    /// Get the FEN symbol for a piece
    /// - Parameters:
    ///   - color: Color of the piece
    ///   - type: Type of the piece
    /// - Returns: FEN symbol (uppercase for white, lowercase for black)
    private func pieceSymbol(color: PieceColor, type: PieceType) -> String {
        let symbol: String
        switch type {
        case .king: symbol = "K"
        case .queen: symbol = "Q"
        case .rook: symbol = "R"
        case .bishop: symbol = "B"
        case .knight: symbol = "N"
        case .pawn: symbol = "P"
        }
        return color == .white ? symbol : symbol.lowercased()
    }
}
