import Foundation
import CoreImage
import Vision

class BoardDetector {
    // Share CIContext to avoid creating too many Metal command queues
    private static let shared = CIContext()
    private var context: CIContext { BoardDetector.shared }
    
    func detectBoard(in image: CIImage) -> CGRect? {
        // Configure rectangle detection request
        let request = VNDetectRectanglesRequest()
        request.minimumAspectRatio = 0.8  // Adjusted for standard chess board
        request.maximumAspectRatio = 1.2
        request.minimumSize = 0.4
        request.maximumObservations = 1
        request.quadratureTolerance = 30
        request.minimumConfidence = 0.9
        
        // Perform the request
        let requestHandler = VNImageRequestHandler(ciImage: image, options: [:])
        do {
            try requestHandler.perform([request])
        } catch {
            print("Failed to perform rectangle detection: \(error)")
            return nil
        }
        
        // Process results
        guard let observations = request.results,
              !observations.isEmpty else {
            return nil
        }
        
        let bestObservation = observations[0]
        
        // Convert Vision coordinates to CoreImage coordinates
        let imageSize = image.extent.size
        let transform = CGAffineTransform(scaleX: imageSize.width, y: imageSize.height)
        
        // Create normalized rect in CoreImage coordinate space
        let detectedRect = bestObservation.boundingBox.applying(transform)
        
        // Validate the detected rectangle
        guard validateDetectedRect(detectedRect, in: image) else {
            return nil
        }
        
        return detectedRect
    }
    
    private func validateDetectedRect(_ rect: CGRect, in image: CIImage) -> Bool {
        let imageSize = image.extent.size
        
        // Check if rectangle is within image bounds
        guard image.extent.contains(rect) else {
            return false
        }
        
        // Validate aspect ratio (standard chess board is square)
        let aspectRatio = rect.width / rect.height
        guard aspectRatio >= 0.9 && aspectRatio <= 1.1 else {
            return false
        }
        
        // Validate size relative to image
        let minDimension = min(imageSize.width, imageSize.height)
        let boardSize = max(rect.width, rect.height)
        guard boardSize >= minDimension * 0.4 else {
            return false
        }
        
        return true
    }
    
}
