#!/usr/bin/env python3
"""
Obsbot Tiny 2 Camera Control
Full control over pan, tilt, zoom, tracking, and AI features
"""

import subprocess
import time
import cv2

class ObsbotCamera:
    """Complete control for Obsbot Tiny 2 AI Camera"""
    
    def __init__(self):
        self.device = '/dev/video0'
        self.current_pan = 0
        self.current_tilt = 0
        self.current_zoom = 1.0
        self.tracking_enabled = False
        
        print("🎥 Initializing Obsbot Tiny 2 camera...")
        self.initialize()
    
    def initialize(self):
        """Initialize camera and detect capabilities"""
        try:
            # Check if camera exists
            result = subprocess.run(
                ['v4l2-ctl', '-d', self.device, '--list-ctrls'],
                capture_output=True,
                text=True,
                timeout=5
            )
            
            if result.returncode == 0:
                print("✅ Obsbot camera detected")
                # Parse available controls
                self.parse_controls(result.stdout)
            else:
                print("⚠️  Camera detected but limited control")
                
        except Exception as e:
            print(f"⚠️  Camera initialization: {e}")
    
    def parse_controls(self, controls_output):
        """Parse available V4L2 controls"""
        self.has_pan_tilt = 'pan' in controls_output.lower()
        self.has_zoom = 'zoom' in controls_output.lower()
        
        if self.has_pan_tilt:
            print("  ✅ Pan/Tilt control available")
        if self.has_zoom:
            print("  ✅ Zoom control available")
    
    def pan(self, angle: float):
        """
        Pan camera (-180 to 180 degrees)
        0 = center, positive = right, negative = left
        """
        angle = max(-180, min(180, angle))
        
        try:
            # Try V4L2 control first
            result = subprocess.run(
                ['v4l2-ctl', '-d', self.device, '--set-ctrl', f'pan_absolute={int(angle * 100)}'],
                capture_output=True,
                timeout=2
            )
            
            if result.returncode == 0:
                self.current_pan = angle
                print(f"📹 Camera panned to {angle}°")
                return True
            else:
                print(f"📹 Pan to {angle}° (simulated - V4L2 control unavailable)")
                self.current_pan = angle
                return False
                
        except Exception as e:
            print(f"📹 Pan to {angle}° (simulated - {e})")
            self.current_pan = angle
            return False
    
    def tilt(self, angle: float):
        """
        Tilt camera (-15 to 45 degrees for Obsbot Tiny 2)
        0 = level, positive = up, negative = down
        """
        angle = max(-15, min(45, angle))
        
        try:
            result = subprocess.run(
                ['v4l2-ctl', '-d', self.device, '--set-ctrl', f'tilt_absolute={int(angle * 100)}'],
                capture_output=True,
                timeout=2
            )
            
            if result.returncode == 0:
                self.current_tilt = angle
                print(f"📹 Camera tilted to {angle}°")
                return True
            else:
                print(f"📹 Tilt to {angle}° (simulated)")
                self.current_tilt = angle
                return False
                
        except Exception as e:
            print(f"📹 Tilt to {angle}° (simulated - {e})")
            self.current_tilt = angle
            return False
    
    def zoom(self, level: float):
        """
        Zoom camera (1.0 to 4.0 for Obsbot Tiny 2)
        1.0 = no zoom, 4.0 = max digital zoom
        """
        level = max(1.0, min(4.0, level))
        zoom_value = int((level - 1.0) * 100)  # Convert to 0-300 range
        
        try:
            result = subprocess.run(
                ['v4l2-ctl', '-d', self.device, '--set-ctrl', f'zoom_absolute={zoom_value}'],
                capture_output=True,
                timeout=2
            )
            
            if result.returncode == 0:
                self.current_zoom = level
                print(f"🔍 Camera zoomed to {level}×")
                return True
            else:
                print(f"🔍 Zoom to {level}× (simulated)")
                self.current_zoom = level
                return False
                
        except Exception as e:
            print(f"🔍 Zoom to {level}× (simulated - {e})")
            self.current_zoom = level
            return False
    
    def center(self):
        """Reset camera to center position"""
        self.pan(0)
        self.tilt(0)
        self.zoom(1.0)
        print("📹 Camera centered")
    
    def enable_tracking(self):
        """Enable AI auto-tracking (if available)"""
        # Obsbot's tracking is typically controlled via their app or button
        self.tracking_enabled = True
        print("🎯 Tracking mode enabled (use Obsbot button/app for full control)")
    
    def disable_tracking(self):
        """Disable AI auto-tracking"""
        self.tracking_enabled = False
        print("🎯 Tracking mode disabled")
    
    def look_left(self):
        """Quick look left"""
        self.pan(-45)
    
    def look_right(self):
        """Quick look right"""
        self.pan(45)
    
    def look_up(self):
        """Quick look up"""
        self.tilt(20)
    
    def look_down(self):
        """Quick look down"""
        self.tilt(-10)
    
    def scan_room(self):
        """Scan the room by panning"""
        print("🔄 Scanning room...")
        positions = [-90, -45, 0, 45, 90, 0]
        for pos in positions:
            self.pan(pos)
            time.sleep(1)
        print("✅ Room scan complete")
    
    def focus_on_human(self):
        """Center and zoom slightly to focus on human"""
        self.center()
        self.zoom(1.5)
        print("👤 Focused on human")
    
    def get_status(self):
        """Get current camera status"""
        return {
            'pan': self.current_pan,
            'tilt': self.current_tilt,
            'zoom': self.current_zoom,
            'tracking': self.tracking_enabled
        }

if __name__ == '__main__':
    print("Testing Obsbot Tiny 2 camera control...")
    
    camera = ObsbotCamera()
    
    print("\n1. Testing pan...")
    camera.pan(45)
    time.sleep(1)
    camera.pan(-45)
    time.sleep(1)
    camera.center()
    
    print("\n2. Testing tilt...")
    camera.tilt(20)
    time.sleep(1)
    camera.tilt(-10)
    time.sleep(1)
    camera.center()
    
    print("\n3. Testing zoom...")
    camera.zoom(2.0)
    time.sleep(1)
    camera.zoom(1.0)
    
    print("\n4. Testing room scan...")
    camera.scan_room()
    
    print("\n5. Current status:")
    print(camera.get_status())
    
    print("\n✅ Test complete!")
