#![deny(warnings)]
#![allow(dead_code)]
//! [TSM.ID].[11031972] -- Platform X Ecosystem
//! xcu-vision-ai -- Eye-Tracking Auto-Framing for Video Calls
#[derive(Debug)] pub enum VisionError { NoFace(String), InvalidFrame(String) }
impl std::fmt::Display for VisionError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::NoFace(e)|Self::InvalidFrame(e) => write!(f, "{e}") } } }
impl std::error::Error for VisionError {}
#[derive(Debug, Clone)] pub struct FaceRegion { pub x: f64, pub y: f64, pub w: f64, pub h: f64, pub confidence: f64 }
#[derive(Debug, Clone)] pub struct CropRect { pub x: f64, pub y: f64, pub w: f64, pub h: f64 }
pub struct SmoothTracker { prev_x: f64, prev_y: f64, alpha: f64 }
impl SmoothTracker {
    pub fn new(alpha: f64) -> Self { Self { prev_x: 0.0, prev_y: 0.0, alpha } }
    pub fn update(&mut self, x: f64, y: f64) -> (f64, f64) {
        self.prev_x = self.alpha * x + (1.0 - self.alpha) * self.prev_x;
        self.prev_y = self.alpha * y + (1.0 - self.alpha) * self.prev_y;
        (self.prev_x, self.prev_y)
    }
}
pub struct AutoFramer { pub margin: f64 }
impl AutoFramer {
    pub fn new(margin: f64) -> Self { Self { margin } }
    pub fn compute_crop(&self, face: &FaceRegion, frame_w: f64, frame_h: f64) -> CropRect {
        let cx = face.x + face.w / 2.0; let cy = face.y + face.h / 2.0;
        let crop_size = (face.w.max(face.h) * (1.0 + self.margin)).min(frame_w.min(frame_h));
        let x = (cx - crop_size / 2.0).max(0.0).min(frame_w - crop_size);
        let y = (cy - crop_size / 2.0).max(0.0).min(frame_h - crop_size);
        CropRect { x, y, w: crop_size, h: crop_size }
    }
    pub fn estimate_distance(&self, face_h: f64, frame_h: f64) -> f64 {
        if face_h <= 0.0 { return f64::MAX; }
        (frame_h / face_h) * 0.5 // rough: face fills half frame at 0.5m
    }
}
pub fn detect_skin_region(pixels_rgb: &[(u8,u8,u8)], w: usize, h: usize) -> Option<FaceRegion> {
    let mut sx=0usize; let mut sy=0usize; let mut count=0usize;
    for (i, &(r,g,b)) in pixels_rgb.iter().enumerate() {
        if r > 95 && g > 40 && b > 20 && r > g && r > b && (r as i32 - g as i32).abs() > 15 {
            sx += i % w; sy += i / w; count += 1;
        }
    }
    if count < 10 { return None; }
    let cx = sx as f64 / count as f64; let cy = sy as f64 / count as f64;
    let size = (count as f64).sqrt() * 2.0;
    Some(FaceRegion { x: cx - size/2.0, y: cy - size/2.0, w: size, h: size, confidence: (count as f64 / (w*h) as f64).min(1.0) })
}
#[cfg(test)] mod tests {
    use super::*;
    #[test] fn test_crop() { let af = AutoFramer::new(0.5); let face = FaceRegion { x: 100.0, y: 100.0, w: 50.0, h: 60.0, confidence: 0.9 }; let crop = af.compute_crop(&face, 640.0, 480.0); assert!(crop.w > 0.0 && crop.x >= 0.0); }
    #[test] fn test_smooth() { let mut t = SmoothTracker::new(0.3); let (x1,_) = t.update(100.0, 100.0); let (x2,_) = t.update(100.0, 100.0); assert!(x2 > x1); }
}
