#!/bin/bash
# Universal HACCPro Sensor Installer
# Works on ALL Raspberry Pi models: Zero, 3, 4, 5, and future versions
# Auto-detects hardware and optimizes accordingly
# Usage: curl -sSL https://iot.haccpro.nl/sensors/install.sh | bash
# Usage: curl -sSL https://iot.haccpro.nl/sensors/install.sh | bash -s -- --company-id 31 --location "Cold Storage"

set -e

# Parse command line arguments
COMPANY_ID=""
COMPANY_LOCATION=""

while [[ $# -gt 0 ]]; do
    case $1 in
        --company-id)
            COMPANY_ID="$2"
            shift 2
            ;;
        --location)
            COMPANY_LOCATION="$2"  
            shift 2
            ;;
        -h|--help)
            echo "Usage: $0 [OPTIONS]"
            echo "Options:"
            echo "  --company-id ID    HACCPro company ID (e.g., 18, 31, 68)"
            echo "  --location LOC     Location name (e.g., 'Cold Storage', 'Freezer')"
            echo "  -h, --help         Show this help"
            echo ""
            echo "Examples:"
            echo "  curl -sSL https://iot.haccpro.nl/sensors/install.sh | bash"
            echo "  curl -sSL https://iot.haccpro.nl/sensors/install.sh | bash -s -- --company-id 31 --location 'Cold Storage'"
            exit 0
            ;;
        *)
            echo "Unknown option: $1"
            exit 1
            ;;
    esac
done

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
NC='\033[0m'

# Global variables
PI_MODEL=""
PI_MEMORY_MB=0
PI_CPU_CORES=0
PI_ARCHITECTURE=""
INSTALL_DIR="/opt/haccpro"
SERVICE_NAME="haccpro-sensor"
USER="haccpro"

print_logo() {
    echo -e "${BLUE}"
    cat << 'EOF'
  ╔══════════════════════════════════════════╗
  ║         🌡️  HACCPro Universal Sensor     ║
  ║       Auto-Detecting Raspberry Pi        ║
  ║          Professional Installation       ║
  ╚══════════════════════════════════════════╝
EOF
    echo -e "${NC}"
}

print_step() { echo -e "${BLUE}[STEP]${NC} $1"; }
print_success() { echo -e "${GREEN}[SUCCESS]${NC} $1"; }
print_error() { echo -e "${RED}[ERROR]${NC} $1"; }
print_info() { echo -e "${PURPLE}[INFO]${NC} $1"; }

# Hardware detection functions
detect_pi_model() {
    print_step "Detecting Raspberry Pi hardware..."

    if [ ! -f /proc/cpuinfo ]; then
        print_error "Cannot detect Pi model - /proc/cpuinfo not found"
        exit 1
    fi

    local revision=$(grep "Revision" /proc/cpuinfo | cut -d':' -f2 | xargs)
    local model=$(grep "Model" /proc/cpuinfo | cut -d':' -f2 | xargs)
    local hardware=$(grep "Hardware" /proc/cpuinfo | cut -d':' -f2 | xargs)

    # Memory detection
    PI_MEMORY_MB=$(free -m | awk '/^Mem:/{print $2}')

    # CPU cores detection
    PI_CPU_CORES=$(nproc)

    # Architecture detection
    PI_ARCHITECTURE=$(uname -m)

    # Model detection based on revision codes and model strings
    case "$revision" in
        *"900021"*|*"900032"*|*"900092"*|*"900093"*|*"920093"*)
            PI_MODEL="Pi Zero" ;;
        *"902120"*)
            PI_MODEL="Pi Zero 2W" ;;
        *"a01040"*|*"a01041"*|*"a21041"*|*"a22042"*)
            PI_MODEL="Pi 2" ;;
        *"a02082"*|*"a020a0"*|*"a22082"*|*"a32082"*)
            PI_MODEL="Pi 3" ;;
        *"a03111"*|*"b03111"*|*"b03112"*|*"c03111"*|*"c03112"*)
            PI_MODEL="Pi 4" ;;
        *"c04170"*|*"d04170"*)
            PI_MODEL="Pi 5" ;;
        *)
            # Fallback to model string parsing for future models
            if echo "$model" | grep -qi "pi zero"; then
                PI_MODEL="Pi Zero"
            elif echo "$model" | grep -qi "pi 2"; then
                PI_MODEL="Pi 2"
            elif echo "$model" | grep -qi "pi 3"; then
                PI_MODEL="Pi 3"
            elif echo "$model" | grep -qi "pi 4"; then
                PI_MODEL="Pi 4"
            elif echo "$model" | grep -qi "pi 5"; then
                PI_MODEL="Pi 5"
            elif echo "$model" | grep -qi "raspberry pi"; then
                # Future Pi model - make educated guess based on specs
                if [ "$PI_MEMORY_MB" -le 512 ]; then
                    PI_MODEL="Pi Zero (Future)"
                elif [ "$PI_MEMORY_MB" -le 1024 ]; then
                    PI_MODEL="Pi 3 (Future)"
                elif [ "$PI_MEMORY_MB" -le 4096 ]; then
                    PI_MODEL="Pi 4 (Future)"
                else
                    PI_MODEL="Pi 5+ (Future)"
                fi
            else
                PI_MODEL="Unknown Pi"
            fi
            ;;
    esac

    print_success "Detected: $PI_MODEL"
    print_info "Memory: ${PI_MEMORY_MB}MB | Cores: $PI_CPU_CORES | Arch: $PI_ARCHITECTURE"
}

# Get hardware-optimized configuration
get_hardware_config() {
    local config_file="/tmp/pi_config.json"

    # Base configuration
    local reading_interval=60
    local log_level="INFO"
    local max_offline_readings=1000
    local heartbeat_interval=300
    local nice_level=0
    local memory_limit="200M"
    local cpu_shares=1024
    local workers=1

    # Optimize based on detected hardware
    case "$PI_MODEL" in
        "Pi Zero"*|"Unknown Pi")
            # Conservative settings for low-power Pi
            reading_interval=120
            log_level="WARNING"
            max_offline_readings=100
            heartbeat_interval=600
            nice_level=10
            memory_limit="80M"
            cpu_shares=512
            ;;
        "Pi 2"*|"Pi 3"*)
            # Moderate settings for mid-range Pi
            reading_interval=60
            log_level="INFO"
            max_offline_readings=500
            heartbeat_interval=300
            nice_level=5
            memory_limit="150M"
            cpu_shares=768
            ;;
        "Pi 4"*)
            # Standard settings for powerful Pi
            reading_interval=30
            log_level="INFO"
            max_offline_readings=1000
            heartbeat_interval=300
            nice_level=0
            memory_limit="200M"
            cpu_shares=1024
            ;;
        "Pi 5"*|*"Future"*)
            # Aggressive settings for high-performance Pi
            reading_interval=30
            log_level="DEBUG"
            max_offline_readings=2000
            heartbeat_interval=180
            nice_level=-5
            memory_limit="300M"
            cpu_shares=1536
            workers=2
            ;;
    esac

    # Adjust for available memory
    if [ "$PI_MEMORY_MB" -le 512 ]; then
        memory_limit="60M"
        max_offline_readings=50
    elif [ "$PI_MEMORY_MB" -le 1024 ]; then
        memory_limit="100M"
        max_offline_readings=200
    elif [ "$PI_MEMORY_MB" -ge 4096 ]; then
        memory_limit="400M"
        max_offline_readings=5000
    fi

    # Export configuration
    cat > "$config_file" << EOF
{
    "pi_model": "$PI_MODEL",
    "pi_memory_mb": $PI_MEMORY_MB,
    "pi_cpu_cores": $PI_CPU_CORES,
    "reading_interval": $reading_interval,
    "log_level": "$log_level",
    "max_offline_readings": $max_offline_readings,
    "heartbeat_interval": $heartbeat_interval,
    "nice_level": $nice_level,
    "memory_limit": "$memory_limit",
    "cpu_shares": $cpu_shares,
    "workers": $workers
}
EOF

    echo "$config_file"
}

# Check system requirements
check_requirements() {
    print_step "Checking system requirements..."

    # Check if running as root
    if [[ $EUID -ne 0 ]]; then
        print_error "Please run as root: sudo bash $0"
        exit 1
    fi

    # Check if this is actually a Raspberry Pi
    if [ "$PI_MODEL" = "Unknown Pi" ] && ! grep -q "BCM" /proc/cpuinfo; then
        print_error "This doesn't appear to be a Raspberry Pi"
        read -p "Continue anyway? (y/N): " -n 1 -r
        echo
        if [[ ! $REPLY =~ ^[Yy]$ ]]; then
            exit 1
        fi
    fi

    # Check minimum requirements
    if [ "$PI_MEMORY_MB" -lt 256 ]; then
        print_error "Insufficient memory: ${PI_MEMORY_MB}MB (minimum 256MB required)"
        exit 1
    fi

    # Check disk space
    local available_space=$(df / | awk 'NR==2 {print $4}')
    if [ "$available_space" -lt 1048576 ]; then  # 1GB in KB
        print_error "Insufficient disk space (minimum 1GB free required)"
        exit 1
    fi

    print_success "System requirements met"
}

# Install system dependencies
install_dependencies() {
    print_step "Installing system dependencies..."

    # Update package list
    print_info "Updating package list..."
    apt-get update -qq

    # Base packages for all Pi models
    local packages=(
        "python3"
        "python3-pip"
        "python3-venv"
        "python3-full"
        "python3-dev"
        "build-essential"
        "curl"
        "wget"
        "git"
        "bc"
        "systemd"
        "rsyslog"
        "nano"
    )

    # Architecture-specific packages
    case "$PI_ARCHITECTURE" in
        "armv6l")
            # Pi Zero 1 - minimal packages
            packages+=("python3-setuptools")
            ;;
        "armv7l")
            # Pi 2/3/4 - standard packages
            packages+=("python3-wheel" "gcc")
            ;;
        "aarch64")
            # Pi 4/5 64-bit - full development packages
            packages+=("python3-wheel" "gcc" "g++" "make")
            ;;
    esac

    # Verify packages are available first
    print_info "Verifying package availability..."
    local missing_packages=()
    
    for package in "${packages[@]}"; do
        if ! apt-cache show "$package" > /dev/null 2>&1; then
            missing_packages+=("$package")
        fi
    done
    
    # Handle missing packages
    if [ ${#missing_packages[@]} -gt 0 ]; then
        print_error "The following packages are not available:"
        for pkg in "${missing_packages[@]}"; do
            echo "  - $pkg"
        done
        
        # Try to handle python3-full specifically
        if [[ " ${missing_packages[@]} " =~ " python3-full " ]]; then
            print_info "python3-full not available, will use python3-venv only"
            # Remove python3-full from packages array
            local new_packages=()
            for pkg in "${packages[@]}"; do
                if [[ "$pkg" != "python3-full" ]]; then
                    new_packages+=("$pkg")
                fi
            done
            packages=("${new_packages[@]}")
        fi
        
        # Check for other critical missing packages
        for missing in "${missing_packages[@]}"; do
            if [[ "$missing" != "python3-full" ]]; then
                print_error "Required package $missing is not available"
                exit 1
            fi
        done
    fi

    # Install packages
    print_info "Installing ${#packages[@]} packages..."
    DEBIAN_FRONTEND=noninteractive apt-get install -y "${packages[@]}"

    print_success "Dependencies installed for $PI_ARCHITECTURE"
}

# Configure hardware interfaces
configure_hardware() {
    print_step "Configuring hardware interfaces..."

    # Enable 1-Wire for temperature sensors
    if ! grep -q "dtoverlay=w1-gpio" /boot/config.txt; then
        echo "dtoverlay=w1-gpio" >> /boot/config.txt
        print_info "1-Wire enabled (reboot required)"
    fi

    # Load 1-Wire modules
    modprobe w1-gpio 2>/dev/null || true
    modprobe w1-therm 2>/dev/null || true

    # Add to modules for auto-load
    echo "w1-gpio" >> /etc/modules 2>/dev/null || true
    echo "w1-therm" >> /etc/modules 2>/dev/null || true

    # Pi model specific optimizations
    case "$PI_MODEL" in
        "Pi Zero"*)
            # Optimize for low power
            echo "gpu_mem=16" >> /boot/config.txt
            echo "arm_freq=800" >> /boot/config.txt  # Conservative frequency
            ;;
        "Pi 2"*|"Pi 3"*)
            # Balanced settings
            echo "gpu_mem=32" >> /boot/config.txt
            ;;
        "Pi 4"*)
            # Performance settings
            echo "gpu_mem=64" >> /boot/config.txt
            ;;
        "Pi 5"*|*"Future"*)
            # High-performance settings
            echo "gpu_mem=128" >> /boot/config.txt
            ;;
    esac

    print_success "Hardware configured for $PI_MODEL"
}

# Create user and directories
setup_user_and_dirs() {
    print_step "Setting up user and directories..."

    # Create haccpro user
    if ! id "$USER" &>/dev/null; then
        useradd --system --shell /bin/bash --home "$INSTALL_DIR" --create-home "$USER"
        usermod -a -G gpio,spi,i2c "$USER" 2>/dev/null || true
        print_success "User $USER created"
    else
        print_info "User $USER already exists"
    fi

    # Create directories
    mkdir -p "$INSTALL_DIR"
    mkdir -p "/etc/haccpro"
    mkdir -p "/var/log/haccpro"
    mkdir -p "/var/lib/haccpro"

    # Set ownership
    chown -R "$USER:$USER" "$INSTALL_DIR" "/etc/haccpro" "/var/log/haccpro" "/var/lib/haccpro"
}

# Install Python environment with hardware optimization
setup_python_environment() {
    print_step "Setting up Python environment..."

    # Create virtual environment
    if [ ! -d "$INSTALL_DIR/venv" ]; then
        print_info "Creating Python virtual environment..."
        if sudo -u "$USER" python3 -m venv "$INSTALL_DIR/venv"; then
            print_success "Virtual environment created"
        else
            print_error "Failed to create virtual environment"
            print_info "Trying alternative method with --system-site-packages..."
            if sudo -u "$USER" python3 -m venv --system-site-packages "$INSTALL_DIR/venv"; then
                print_success "Virtual environment created with system packages access"
            else
                print_error "Virtual environment creation failed. Please ensure python3-venv and python3-full are installed."
                exit 1
            fi
        fi
    fi

    # Upgrade pip
    print_info "Upgrading pip..."
    if ! sudo -u "$USER" "$INSTALL_DIR/venv/bin/pip" install --upgrade pip; then
        print_error "Failed to upgrade pip, continuing with existing version..."
    fi

    # Install packages based on Pi model and architecture
    local pip_packages="aiohttp aiofiles psutil requests"

    # Add performance monitoring for powerful Pi models
    case "$PI_MODEL" in
        "Pi 4"*|"Pi 5"*|*"Future"*)
            pip_packages="$pip_packages numpy"  # For advanced analytics
            ;;
    esac

    print_info "Installing Python packages: $pip_packages"

    # Install with architecture-specific optimizations
    case "$PI_ARCHITECTURE" in
        "armv6l")
            # Pi Zero - use pre-built wheels where possible
            print_info "Installing for Pi Zero (armv6l) with pre-built wheels..."
            if ! sudo -u "$USER" "$INSTALL_DIR/venv/bin/pip" install --only-binary=all $pip_packages; then
                print_info "Pre-built wheels failed, trying with compilation..."
                if ! sudo -u "$USER" "$INSTALL_DIR/venv/bin/pip" install $pip_packages; then
                    print_error "Package installation failed. Check your internet connection and try again."
                    exit 1
                fi
            fi
            ;;
        *)
            # More powerful Pi - can compile if needed
            print_info "Installing for more powerful Pi ($PI_ARCHITECTURE)..."
            if ! sudo -u "$USER" "$INSTALL_DIR/venv/bin/pip" install $pip_packages; then
                print_error "Package installation failed. Check your internet connection and try again."
                exit 1
            fi
            ;;
    esac

    print_success "Python environment ready"
}

# Create the sensor application with hardware-specific optimizations
create_sensor_application() {
    print_step "Creating sensor application..."

    local config_file=$(get_hardware_config)
    local pi_config=$(cat "$config_file")

    cat > "$INSTALL_DIR/sensor.py" << 'SENSOR_APP_EOF'
#!/usr/bin/env python3
"""
HACCPro Universal Temperature Sensor
Auto-optimizes for any Raspberry Pi model
"""

import asyncio
import aiohttp
import json
import logging
import time
import glob
import os
import sys
import signal
import gc
import psutil
from datetime import datetime
from pathlib import Path
from typing import Optional, Dict, List
from dataclasses import dataclass, asdict
import argparse

# Hardware configuration (injected during installation)
HARDWARE_CONFIG = PI_CONFIG_PLACEHOLDER

@dataclass
class SensorConfig:
    device_id: str = ""
    name: str = ""
    location: str = ""
    api_key: str = ""
    api_url: str = "https://api.haccpro.nl/api/v1"
    company_id: str = "18"
    sensor_id: Optional[str] = None
    reading_interval: int = HARDWARE_CONFIG["reading_interval"]
    temp_min: float = -25.0
    temp_max: float = -15.0
    log_level: str = HARDWARE_CONFIG["log_level"]
    max_offline_readings: int = HARDWARE_CONFIG["max_offline_readings"]
    heartbeat_interval: int = HARDWARE_CONFIG["heartbeat_interval"]

class PiOptimizer:
    """Hardware-specific optimizations"""

    def __init__(self):
        self.pi_model = HARDWARE_CONFIG["pi_model"]
        self.memory_mb = HARDWARE_CONFIG["pi_memory_mb"]
        self.apply_optimizations()

    def apply_optimizations(self):
        """Apply hardware-specific optimizations"""
        if self.memory_mb <= 512:
            # Low memory optimizations
            gc.set_threshold(700, 10, 10)
        elif self.memory_mb >= 4096:
            # High memory optimizations
            gc.set_threshold(2000, 25, 25)

    def get_system_stats(self) -> Dict:
        """Get current system statistics"""
        try:
            memory = psutil.virtual_memory()
            cpu_percent = psutil.cpu_percent(interval=1)

            # Try to get CPU temperature
            cpu_temp = None
            try:
                with open('/sys/class/thermal/thermal_zone0/temp', 'r') as f:
                    cpu_temp = int(f.read()) / 1000.0
            except:
                pass

            return {
                'memory_percent': memory.percent,
                'memory_available_mb': memory.available // (1024 * 1024),
                'cpu_percent': cpu_percent,
                'cpu_temp': cpu_temp,
                'pi_model': self.pi_model
            }
        except Exception as e:
            return {'error': str(e)}

class DS18B20Sensor:
    """Universal DS18B20 sensor interface"""

    def __init__(self, sensor_id: Optional[str] = None):
        self.base_dir = '/sys/bus/w1/devices/'
        self.sensor_id = sensor_id or self.detect_sensor()
        self.device_path = f"{self.base_dir}{self.sensor_id}/w1_slave" if self.sensor_id else None

    def detect_sensor(self) -> Optional[str]:
        """Auto-detect DS18B20 sensor"""
        try:
            device_folders = glob.glob(f"{self.base_dir}28-*")
            return os.path.basename(device_folders[0]) if device_folders else None
        except:
            return None

    def read_temperature(self) -> Optional[float]:
        """Read temperature with validation"""
        if not self.device_path or not os.path.exists(self.device_path):
            return None

        try:
            with open(self.device_path, 'r') as f:
                lines = f.readlines()

            if not lines[0].strip().endswith('YES'):
                return None

            temp_line = lines[1]
            equals_pos = temp_line.find('t=')
            if equals_pos != -1:
                temp_string = temp_line[equals_pos + 2:]
                temp_c = float(temp_string) / 1000.0

                if -55 <= temp_c <= 125:
                    return round(temp_c, 2)

            return None
        except Exception as e:
            logging.error(f"Sensor read error: {e}")
            return None

    def get_info(self) -> Dict[str, str]:
        return {
            "sensor_id": self.sensor_id or "Not detected",
            "status": "connected" if self.device_path and os.path.exists(self.device_path) else "disconnected"
        }

class HACCProAPIClient:
    """Optimized API client"""

    def __init__(self, config: SensorConfig):
        self.config = config
        self.session: Optional[aiohttp.ClientSession] = None
        self.offline_readings = []

    async def __aenter__(self):
        # Use hardware-appropriate connection settings
        connector = aiohttp.TCPConnector(
            limit=HARDWARE_CONFIG.get("workers", 1),
            limit_per_host=1,
            ttl_dns_cache=300,
            use_dns_cache=True
        )

        self.session = aiohttp.ClientSession(
            connector=connector,
            timeout=aiohttp.ClientTimeout(total=30),
            headers={
                'X-API-Key': self.config.api_key,
                'Content-Type': 'application/json',
                'User-Agent': f'HACCPro-Sensor/2.0-{HARDWARE_CONFIG["pi_model"].replace(" ", "")}'
            }
        )
        return self

    async def __aexit__(self, exc_type, exc_val, exc_tb):
        if self.session:
            await self.session.close()

    async def submit_temperature(self, temperature: float) -> bool:
        """Submit temperature reading"""
        data = {
            "device_id": self.config.device_id,
            "temperature": temperature,
            "unit": "celsius",
            "timestamp": datetime.utcnow().isoformat(),
            "pi_model": HARDWARE_CONFIG["pi_model"]
        }

        try:
            url = f"{self.config.api_url}/device/temperature"
            async with self.session.post(url, json=data) as response:
                if response.status == 200:
                    result = await response.json()

                    alerts = result.get('alerts', [])
                    if alerts:
                        logging.warning(f"🚨 {len(alerts)} ALERT(S)!")
                        for alert in alerts:
                            logging.error(f"   📧 {alert.get('type', 'UNKNOWN')}: {alert.get('message', '')}")

                    logging.info(f"✅ {temperature}°C submitted")
                    return True
                else:
                    logging.error(f"❌ API error {response.status}")
                    return False

        except Exception as e:
            logging.warning(f"🌐 Network error, storing offline: {e}")
            if len(self.offline_readings) < self.config.max_offline_readings:
                self.offline_readings.append(data)
            return False

    async def heartbeat(self) -> bool:
        """Send heartbeat with system stats"""
        try:
            optimizer = PiOptimizer()
            stats = optimizer.get_system_stats()

            url = f"{self.config.api_url}/device/heartbeat/{self.config.device_id}"
            async with self.session.post(url, json={"stats": stats}) as response:
                return response.status == 200
        except:
            return False

    async def sync_offline_readings(self) -> int:
        """Upload offline readings"""
        if not self.offline_readings:
            return 0

        uploaded = 0
        for reading in self.offline_readings[:]:
            try:
                url = f"{self.config.api_url}/device/temperature"
                async with self.session.post(url, json=reading) as response:
                    if response.status == 200:
                        self.offline_readings.remove(reading)
                        uploaded += 1
                    else:
                        break
            except:
                break

        if uploaded > 0:
            logging.info(f"📤 Uploaded {uploaded} offline readings")

        return uploaded

class UniversalHACCProSensor:
    """Universal sensor application for all Pi models"""

    def __init__(self, config_path: str = "/etc/haccpro/config.json"):
        self.config_path = config_path
        self.config = self.load_config()
        self.sensor = DS18B20Sensor(self.config.sensor_id)
        self.optimizer = PiOptimizer()
        self.running = False
        self.setup_logging()

        logging.info(f"🤖 HACCPro Universal Sensor v2.0")
        logging.info(f"🔧 Hardware: {HARDWARE_CONFIG['pi_model']} ({HARDWARE_CONFIG['pi_memory_mb']}MB)")
        logging.info(f"📍 Device: {self.config.device_id}")

    def setup_logging(self):
        """Setup logging with hardware-appropriate levels"""
        log_format = '%(asctime)s - %(levelname)s - %(message)s'

        handlers = [logging.StreamHandler()]

        # Only log to file on Pi models with sufficient storage
        if HARDWARE_CONFIG["pi_memory_mb"] >= 512:
            handlers.append(logging.FileHandler('/var/log/haccpro/sensor.log'))

        logging.basicConfig(
            level=getattr(logging, self.config.log_level),
            format=log_format,
            handlers=handlers
        )

    def load_config(self) -> SensorConfig:
        """Load configuration"""
        try:
            with open(self.config_path, 'r') as f:
                data = json.load(f)
            config = SensorConfig(**data)

            # Apply hardware optimizations to config
            config.reading_interval = max(config.reading_interval, HARDWARE_CONFIG["reading_interval"])
            config.max_offline_readings = min(config.max_offline_readings, HARDWARE_CONFIG["max_offline_readings"])
            config.heartbeat_interval = max(config.heartbeat_interval, HARDWARE_CONFIG["heartbeat_interval"])

            return config
        except FileNotFoundError:
            return SensorConfig()
        except Exception as e:
            logging.error(f"Config error: {e}")
            return SensorConfig()

    def save_config(self, config: SensorConfig):
        """Save configuration"""
        os.makedirs(os.path.dirname(self.config_path), exist_ok=True)
        with open(self.config_path, 'w') as f:
            json.dump(asdict(config), f, indent=2)
        logging.info(f"✅ Config saved to {self.config_path}")

    def configure_interactive(self) -> SensorConfig:
        """Interactive configuration with hardware detection"""
        print(f"\n🤖 HACCPro Universal Sensor Configuration")
        print(f"Hardware: {HARDWARE_CONFIG['pi_model']} ({HARDWARE_CONFIG['pi_memory_mb']}MB)")
        print("=" * 60)

        config = SensorConfig()

        # Device configuration
        config.device_id = input("Device ID (e.g. KITCHEN_FREEZER_001): ").strip()
        while not config.device_id:
            config.device_id = input("Device ID (required): ").strip()

        config.name = input(f"Device Name [{config.device_id}]: ").strip() or config.device_id
        config.location = input("Location (e.g. Main Kitchen): ").strip() or "Unknown"
        
        # Company ID configuration
        print(f"\\n🏢 Company Setup")
        print("================")
        config.company_id = input(f"Company ID [{config.company_id}]: ").strip() or config.company_id

        # API Key configuration with automatic generation
        print(f"\\n🔑 API Key Setup")
        print("================")
        print("HACCPro 2.0 requires an API key for secure authentication.")
        print("You can either:")
        print("  1️⃣  Get an API key from the HACCPro dashboard")
        print("  2️⃣  Let us generate one automatically")
        print()
        
        choice = input("Choose option (1/2) [2]: ").strip() or "2"
        
        if choice == "1":
            config.api_key = input("Enter your API Key: ").strip()
            while not config.api_key:
                config.api_key = input("API Key (required): ").strip()
        else:
            # Automatic API key generation
            print("🔄 Generating API key automatically...")
            try:
                import urllib.request
                import urllib.parse
                import json
                
                # Prepare data for device registration
                data = {
                    "device_id": config.device_id,
                    "name": config.name,
                    "location": config.location,
                    "description": f"Auto-registered {HARDWARE_CONFIG['pi_model']} sensor"
                }
                
                # Make request to register device and get API key
                req_data = json.dumps(data).encode()
                req = urllib.request.Request(
                    f"{config.api_url}/device/register",
                    data=req_data,
                    headers={'Content-Type': 'application/json'}
                )
                
                with urllib.request.urlopen(req, timeout=15) as response:
                    result = json.loads(response.read().decode())
                    
                    if result.get("status") == "success":
                        config.api_key = result.get("api_key")
                        print(f"✅ API Key generated: {config.api_key[:20]}...")
                        print(f"📋 Device registered in HACCPro system")
                    else:
                        print(f"❌ Failed to generate API key: {result.get('message', 'Unknown error')}")
                        config.api_key = input("Please enter API key manually: ").strip()
                        
            except Exception as e:
                print(f"❌ Could not auto-generate API key: {e}")
                print("Please get an API key from the HACCPro dashboard")
                config.api_key = input("Enter your API Key: ").strip()
                while not config.api_key:
                    config.api_key = input("API Key (required): ").strip()

        # Sensor detection
        sensor_info = self.sensor.get_info()
        if sensor_info["status"] == "connected":
            config.sensor_id = sensor_info["sensor_id"]
            print(f"✅ Detected sensor: {config.sensor_id}")

            temp = self.sensor.read_temperature()
            if temp is not None:
                print(f"✅ Current temperature: {temp}°C")
        else:
            print("❌ No sensor detected - check wiring")
            config.sensor_id = input("Enter sensor ID manually (optional): ").strip() or None

        # Temperature thresholds
        try:
            config.temp_min = float(input(f"Minimum temperature [{config.temp_min}]: ") or config.temp_min)
            config.temp_max = float(input(f"Maximum temperature [{config.temp_max}]: ") or config.temp_max)
        except ValueError:
            print("Using default thresholds")

        # Hardware-optimized intervals
        print(f"\n🔧 Hardware Optimizations for {HARDWARE_CONFIG['pi_model']}:")
        print(f"  Reading interval: {config.reading_interval}s (optimized)")
        print(f"  Max offline storage: {config.max_offline_readings} readings")
        print(f"  Log level: {config.log_level}")

        return config

    async def run_monitoring_loop(self):
        """Hardware-optimized monitoring loop"""
        self.running = True
        logging.info(f"🚀 Starting monitoring (optimized for {HARDWARE_CONFIG['pi_model']})")

        if not self.config.device_id or not self.config.api_key:
            logging.error("❌ Not configured. Run: sudo haccpro-configure")
            return

        consecutive_errors = 0
        max_errors = 10 if HARDWARE_CONFIG["pi_memory_mb"] >= 1024 else 5
        last_heartbeat = 0
        last_gc = 0

        async with HACCProAPIClient(self.config) as api:
            await api.sync_offline_readings()

            while self.running:
                try:
                    # Read temperature
                    temperature = self.sensor.read_temperature()

                    if temperature is not None:
                        success = await api.submit_temperature(temperature)
                        consecutive_errors = 0 if success else consecutive_errors + 1

                        # Local threshold checking
                        if temperature < self.config.temp_min:
                            logging.error(f"🥶 LOCAL: {temperature}°C < {self.config.temp_min}°C")
                        elif temperature > self.config.temp_max:
                            logging.error(f"🔥 LOCAL: {temperature}°C > {self.config.temp_max}°C")
                    else:
                        logging.warning("❌ Sensor read failed")
                        consecutive_errors += 1

                    # Heartbeat
                    if time.time() - last_heartbeat > self.config.heartbeat_interval:
                        await api.heartbeat()
                        await api.sync_offline_readings()
                        last_heartbeat = time.time()

                    # Memory management for low-memory Pi
                    if HARDWARE_CONFIG["pi_memory_mb"] <= 1024 and time.time() - last_gc > 300:
                        gc.collect()
                        last_gc = time.time()

                    # Error threshold check
                    if consecutive_errors >= max_errors:
                        logging.error(f"❌ Too many errors, stopping")
                        break

                except KeyboardInterrupt:
                    logging.info("🛑 Stopped by user")
                    break
                except Exception as e:
                    logging.error(f"❌ Error: {e}")
                    consecutive_errors += 1

                await asyncio.sleep(self.config.reading_interval)

        self.running = False
        logging.info("🛑 Monitoring stopped")

# Signal handlers
def signal_handler(signum, frame):
    print("\n🛑 Shutting down...")
    sys.exit(0)

async def main():
    """Main entry point"""
    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)

    parser = argparse.ArgumentParser(description='HACCPro Universal Temperature Sensor')
    parser.add_argument('--configure', action='store_true', help='Configuration wizard')
    parser.add_argument('--test', action='store_true', help='Test sensor and API')
    parser.add_argument('--stats', action='store_true', help='Show system stats')
    parser.add_argument('--config', default='/etc/haccpro/config.json', help='Config file')

    args = parser.parse_args()

    sensor_app = UniversalHACCProSensor(args.config)

    if args.configure:
        config = sensor_app.configure_interactive()
        sensor_app.save_config(config)
        print(f"\n✅ Configuration complete for {HARDWARE_CONFIG['pi_model']}!")
        print("🚀 Start: sudo systemctl start haccpro-sensor")
        return

    if args.stats:
        stats = sensor_app.optimizer.get_system_stats()
        print(f"📊 System Stats for {HARDWARE_CONFIG['pi_model']}:")
        for key, value in stats.items():
            print(f"  {key}: {value}")
        return

    if args.test:
        print(f"🧪 Testing on {HARDWARE_CONFIG['pi_model']}...")

        # Test sensor
        temp = sensor_app.sensor.read_temperature()
        print(f"{'✅' if temp else '❌'} Sensor: {temp}°C" if temp else "No reading")

        # Test API
        if sensor_app.config.api_key:
            async with HACCProAPIClient(sensor_app.config) as api:
                success = await api.submit_temperature(temp or -20.0)
                print(f"{'✅' if success else '❌'} API: {'Connected' if success else 'Failed'}")
        return

    # Run monitoring
    await sensor_app.run_monitoring_loop()

if __name__ == "__main__":
    asyncio.run(main())
SENSOR_APP_EOF

    # Replace the placeholder with actual hardware config
    local pi_config_json=$(cat "$config_file" | sed 's/"/\\"/g' | tr -d '\n')
    sed -i "s/PI_CONFIG_PLACEHOLDER/$pi_config_json/g" "$INSTALL_DIR/sensor.py"

    chmod +x "$INSTALL_DIR/sensor.py"
    chown "$USER:$USER" "$INSTALL_DIR/sensor.py"

    # Sensor config is now handled by /etc/haccpro/config.json
    # Remove old sensor_config.json if it exists
    rm -f "$INSTALL_DIR/sensor_config.json"
    
    print_success "Universal sensor application created"
    print_success "Sensor configured for Company ID: $COMPANY_ID, Location: $COMPANY_LOCATION"

    # Cleanup temp config file
    rm -f "$config_file"
}

# Create sensor heartbeat script
create_sensor_heartbeat() {
    print_step "Creating sensor heartbeat system..."

    cat > "$INSTALL_DIR/sensor_heartbeat.py" << 'HEARTBEAT_EOF'
#!/usr/bin/env python3
"""
HACCPro Sensor Heartbeat Script
Reports sensor status and manages remote commands from dashboard
"""

import requests
import json
import time
import subprocess
import psutil
import os
import glob
from datetime import datetime

# Load configuration
CONFIG_FILE = "/etc/haccpro/config.json"
HEARTBEAT_INTERVAL = 30  # seconds

def load_config():
    try:
        with open(CONFIG_FILE, 'r') as f:
            return json.load(f)
    except Exception as e:
        print(f"Error loading config: {e}")
        return {}

def get_local_ip():
    """Get the local IP address of the Raspberry Pi"""
    try:
        import socket
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(("8.8.8.8", 80))
        ip = s.getsockname()[0]
        s.close()
        return ip
    except:
        return "192.168.1.100"  # fallback

def get_uptime():
    """Get system uptime in human readable format"""
    try:
        uptime_seconds = time.time() - psutil.boot_time()
        days = int(uptime_seconds // 86400)
        hours = int((uptime_seconds % 86400) // 3600)
        minutes = int((uptime_seconds % 3600) // 60)
        
        if days > 0:
            return f"{days}d {hours}h {minutes}m"
        elif hours > 0:
            return f"{hours}h {minutes}m"
        else:
            return f"{minutes}m"
    except:
        return "Unknown"

def get_sensor_status():
    """Get sensor hardware status"""
    try:
        # Check if DS18B20 sensors are detected
        sensor_count = len(glob.glob('/sys/bus/w1/devices/28-*'))
        return "online" if sensor_count > 0 else "no_sensors"
    except:
        return "unknown"

def get_temperature_reading():
    """Get current temperature reading"""
    try:
        sensor_files = glob.glob('/sys/bus/w1/devices/28-*/w1_slave')
        if sensor_files:
            with open(sensor_files[0], 'r') as f:
                lines = f.readlines()
            if len(lines) >= 2 and 'YES' in lines[0]:
                temp_pos = lines[1].find('t=')
                if temp_pos != -1:
                    temp_c = float(lines[1][temp_pos+2:]) / 1000.0
                    return temp_c
    except:
        pass
    return None

def send_heartbeat(config):
    """Send heartbeat to dashboard"""
    try:
        ip_address = get_local_ip()
        uptime = get_uptime()
        sensor_status = get_sensor_status()
        temperature = get_temperature_reading()
        
        payload = {
            'device_id': config.get('device_id', 'unknown'),
            'sensor_status': sensor_status,
            'temperature': temperature,
            'location': config.get('location', 'Unknown'),
            'company_id': config.get('company_id', '18')
        }
        
        dashboard_url = config.get('api_url', 'https://api.haccpro.nl')
        api_key = config.get('api_key', '')
        
        headers = {
            'Content-Type': 'application/json'
        }
        if api_key:
            headers['X-API-Key'] = api_key
            
        response = requests.post(
            f"{dashboard_url}/sensors/status",
            json=payload,
            timeout=10,
            headers=headers
        )
        
        if response.status_code == 200:
            print(f"✓ Heartbeat sent successfully at {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
            return True
        else:
            print(f"✗ Heartbeat failed with status {response.status_code}")
            return False
            
    except Exception as e:
        print(f"✗ Error sending heartbeat: {e}")
        return False

def check_for_commands(config):
    """Check for pending commands from dashboard"""
    try:
        dashboard_url = config.get('api_url', 'https://api.haccpro.nl')
        response = requests.get(
            f"{dashboard_url}/sensors/command",
            params={'device_id': config.get('device_id'), 'company_id': config.get('company_id', '18')},
            timeout=10
        )
        
        if response.status_code == 200:
            data = response.json()
            commands = data.get('commands', [])
            
            for command in commands:
                print(f"Received command: {command['command']}")
                execute_command(command)
                
    except Exception as e:
        print(f"Error checking for commands: {e}")

def execute_command(command):
    """Execute a command received from the dashboard"""
    cmd_type = command['command']
    params = command.get('parameters', {})
    
    if cmd_type == 'restart_sensor':
        print("Executing sensor restart...")
        try:
            subprocess.run(['sudo', 'systemctl', 'restart', 'haccpro-sensor'], timeout=30)
            print("Sensor restart completed successfully")
        except Exception as e:
            print(f"Sensor restart failed: {e}")
            
    elif cmd_type == 'get_status':
        print("Executing status check...")
        # Status will be sent with next heartbeat
        
def main():
    """Main heartbeat loop"""
    config = load_config()
    if not config:
        print("No configuration found, exiting")
        return
        
    print(f"Starting HACCPro Sensor Heartbeat")
    print(f"Company ID: {config.get('company_id', 'unknown')}")
    print(f"Location: {config.get('location', 'unknown')}")
    print(f"Heartbeat interval: {HEARTBEAT_INTERVAL} seconds")
    print("-" * 50)
    
    while True:
        try:
            # Send heartbeat
            send_heartbeat(config)
            
            # Check for commands
            check_for_commands(config)
            
            # Wait for next heartbeat
            time.sleep(HEARTBEAT_INTERVAL)
            
        except KeyboardInterrupt:
            print("\nHeartbeat stopped by user")
            break
        except Exception as e:
            print(f"Unexpected error: {e}")
            time.sleep(HEARTBEAT_INTERVAL)

if __name__ == "__main__":
    main()
HEARTBEAT_EOF

    chmod +x "$INSTALL_DIR/sensor_heartbeat.py"
    chown "$USER:$USER" "$INSTALL_DIR/sensor_heartbeat.py"
    
    print_success "Sensor heartbeat system created"
}

# Create hardware-optimized systemd service
create_systemd_service() {
    print_step "Creating optimized systemd service..."

    local config_file=$(get_hardware_config)
    local nice_level=$(jq -r '.nice_level' "$config_file")
    local memory_limit=$(jq -r '.memory_limit' "$config_file")
    local cpu_shares=$(jq -r '.cpu_shares' "$config_file")

    cat > "/etc/systemd/system/$SERVICE_NAME.service" << EOF
[Unit]
Description=HACCPro Universal Temperature Sensor ($PI_MODEL)
Documentation=https://haccpro.nl
After=network.target
Wants=network-online.target

[Service]
Type=simple
User=$USER
Group=$USER
WorkingDirectory=$INSTALL_DIR
Environment="PATH=$INSTALL_DIR/venv/bin"
ExecStart=$INSTALL_DIR/venv/bin/python3 $INSTALL_DIR/sensor.py
Restart=always
RestartSec=30
StartLimitInterval=300
StartLimitBurst=3

# Hardware-optimized resource limits
Nice=$nice_level
MemoryLimit=$memory_limit
CPUShares=$cpu_shares

# Logging
StandardOutput=journal
StandardError=journal
SyslogIdentifier=haccpro-sensor

# Security
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=$INSTALL_DIR /etc/haccpro /var/log/haccpro /var/lib/haccpro /sys/bus/w1
ProtectKernelTunables=true
ProtectKernelModules=true
ProtectControlGroups=true

[Install]
WantedBy=multi-user.target
EOF

    # Create heartbeat service
    cat > "/etc/systemd/system/haccpro-sensor-heartbeat.service" << EOF
[Unit]
Description=HACCPro Sensor Heartbeat
After=network.target haccpro-sensor.service
Wants=haccpro-sensor.service

[Service]
Type=simple
User=$USER
Group=$USER
WorkingDirectory=$INSTALL_DIR
Environment=PYTHONPATH=$INSTALL_DIR/venv/lib/python3.11/site-packages
ExecStart=$INSTALL_DIR/venv/bin/python3 $INSTALL_DIR/sensor_heartbeat.py
Restart=always
RestartSec=10
StandardOutput=journal
StandardError=journal

# Security settings
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=$INSTALL_DIR /etc/haccpro
PrivateTmp=true

[Install]
WantedBy=multi-user.target
EOF

    systemctl daemon-reload
    systemctl enable "$SERVICE_NAME"
    systemctl enable "haccpro-sensor-heartbeat"

    print_success "Services created with $PI_MODEL optimizations"
    print_success "Heartbeat service enabled for dashboard integration"

    rm -f "$config_file"
}

# Create universal management commands
create_management_commands() {
    print_step "Creating management commands..."

    # Universal configuration command
    cat > "/usr/local/bin/haccpro-configure" << 'EOF'
#!/bin/bash
if [[ $EUID -ne 0 ]]; then
    echo "❌ Run with sudo: sudo haccpro-configure"
    exit 1
fi

echo "🤖 HACCPro Universal Sensor Configuration"
sudo -u haccpro /opt/haccpro/venv/bin/python3 /opt/haccpro/sensor.py --configure

if [ $? -eq 0 ]; then
    echo "✅ Configuration complete!"
    echo "🚀 Start: sudo systemctl start haccpro-sensor"
    echo "📊 Status: haccpro-status"
fi
EOF

    # Universal status command
    cat > "/usr/local/bin/haccpro-status" << 'EOF'
#!/bin/bash
echo "🤖 HACCPro Universal Sensor Status"
echo "=================================="

# Hardware info
if [ -f "/opt/haccpro/sensor.py" ]; then
    hw_info=$(sudo -u haccpro /opt/haccpro/venv/bin/python3 /opt/haccpro/sensor.py --stats 2>/dev/null | grep "pi_model\|memory_percent\|cpu_percent\|cpu_temp")
    if [ -n "$hw_info" ]; then
        echo "🔧 Hardware:"
        echo "$hw_info" | sed 's/^/  /'
    fi
fi

# Service status
echo "📟 Service:"
if systemctl is-active haccpro-sensor --quiet; then
    echo "  ✅ Running"
    uptime=$(systemctl show haccpro-sensor --property=ActiveEnterTimestamp --value)
    if [ -n "$uptime" ]; then
        echo "  🕐 Started: $(date -d "$uptime" +'%Y-%m-%d %H:%M:%S')"
    fi
else
    echo "  ❌ Stopped"
fi

# Configuration
if [ -f "/etc/haccpro/config.json" ]; then
    echo "⚙️ Configuration:"
    python3 -c "
import json
try:
    with open('/etc/haccpro/config.json') as f:
        config = json.load(f)
    print(f'  Device: {config.get(\"device_id\", \"Not set\")}')
    print(f'  Location: {config.get(\"location\", \"Not set\")}')
    print(f'  Interval: {config.get(\"reading_interval\", \"60\")}s')
    print(f'  Thresholds: {config.get(\"temp_min\", \"?\")}-{config.get(\"temp_max\", \"?\")}°C')
except Exception as e:
    print(f'  ❌ Error: {e}')
" 2>/dev/null || echo "  ❌ Cannot read config"
else
    echo "⚙️ Configuration: ❌ Not configured"
fi

# Sensor hardware
echo "🌡️ Sensors:"
sensors=$(ls /sys/bus/w1/devices/28-* 2>/dev/null | wc -l)
if [ "$sensors" -gt 0 ]; then
    echo "  ✅ $sensors DS18B20 sensor(s) detected"
    for sensor in /sys/bus/w1/devices/28-*; do
        sensor_id=$(basename "$sensor")
        if [ -f "$sensor/w1_slave" ]; then
            temp_raw=$(tail -1 "$sensor/w1_slave" 2>/dev/null | grep -o 't=.*' | cut -d'=' -f2)
            if [ -n "$temp_raw" ] && [ "$temp_raw" != "0" ]; then
                temp_c=$(echo "scale=1; $temp_raw / 1000" | bc -l 2>/dev/null || echo "?")
                echo "    📟 $sensor_id: ${temp_c}°C"
            else
                echo "    📟 $sensor_id: (no reading)"
            fi
        fi
    done
else
    echo "  ❌ No sensors detected"
fi

# Recent activity
echo "📋 Recent Activity:"
journalctl -u haccpro-sensor --no-pager -n 3 --since "5 minutes ago" 2>/dev/null | tail -3 | sed 's/^/  /' || echo "  No recent activity"
EOF

    # Universal test command
    cat > "/usr/local/bin/haccpro-test" << 'EOF'
#!/bin/bash
if [[ $EUID -ne 0 ]]; then
    echo "❌ Run with sudo: sudo haccpro-test"
    exit 1
fi

echo "🧪 HACCPro Universal Sensor Test"
echo "================================"

if [ ! -f "/etc/haccpro/config.json" ]; then
    echo "❌ Not configured. Run: sudo haccpro-configure"
    exit 1
fi

sudo -u haccpro /opt/haccpro/venv/bin/python3 /opt/haccpro/sensor.py --test
EOF

    # Universal logs command
    cat > "/usr/local/bin/haccpro-logs" << 'EOF'
#!/bin/bash
echo "📋 HACCPro Universal Sensor Logs"
echo "================================"

if [ "$1" = "-f" ] || [ "$1" = "--follow" ]; then
    echo "Following live logs (Ctrl+C to stop)..."
    journalctl -u haccpro-sensor -f
else
    echo "Recent logs (last 20 lines):"
    journalctl -u haccpro-sensor --no-pager -n 20
    echo ""
    echo "💡 Use 'haccpro-logs -f' to follow live logs"
fi
EOF

    # Make all commands executable
    chmod +x /usr/local/bin/haccpro-*

    print_success "Universal management commands created"
}

# Detect sensors
detect_sensors() {
    print_step "Detecting temperature sensors..."

    sleep 2  # Allow time for modules to load

    # Count actual sensor directories that exist
    local sensor_count=0
    local sensor_list=()
    
    # Find all 28-* directories (DS18B20 sensors)
    for sensor_path in /sys/bus/w1/devices/28-*; do
        if [ -d "$sensor_path" ] && [ -f "$sensor_path/w1_slave" ]; then
            sensor_count=$((sensor_count + 1))
            sensor_list+=("$sensor_path")
        fi
    done

    if [ "$sensor_count" -gt 0 ]; then
        print_success "Found $sensor_count DS18B20 sensor(s):"
        for sensor in "${sensor_list[@]}"; do
            local sensor_id=$(basename "$sensor")
            if [ -f "$sensor/w1_slave" ]; then
                local temp_raw=$(tail -1 "$sensor/w1_slave" 2>/dev/null | grep -o 't=.*' | cut -d'=' -f2)
                if [ -n "$temp_raw" ] && [ "$temp_raw" != "0" ]; then
                    local temp_c=$(echo "scale=1; $temp_raw / 1000" | bc -l 2>/dev/null || echo "?")
                    print_info "📟 $sensor_id: ${temp_c}°C"
                else
                    print_info "📟 $sensor_id: (no reading)"
                fi
            fi
        done
    else
        echo "  ❌ No DS18B20 sensors detected"
        echo "  💡 Check wiring: VCC→Pin1, GND→Pin6, Data→Pin7 + 4.7kΩ resistor"
        echo "  💡 Enable 1-Wire: sudo raspi-config → Interface Options → 1-Wire"
    fi
}

# Final completion message
print_completion() {
    echo
    echo -e "${GREEN}╔══════════════════════════════════════════╗${NC}"
    echo -e "${GREEN}║  🎉 HACCPro Universal Installation Done! ║${NC}"
    echo -e "${GREEN}╚══════════════════════════════════════════╝${NC}"
    echo
    echo -e "${PURPLE}Hardware Detected: $PI_MODEL${NC}"
    echo -e "${PURPLE}Memory: ${PI_MEMORY_MB}MB | Cores: $PI_CPU_CORES | Architecture: $PI_ARCHITECTURE${NC}"
    echo
    echo -e "${BLUE}📋 Next Steps:${NC}"
    echo -e "  1️⃣  Configure: ${YELLOW}sudo haccpro-configure${NC}"
    echo -e "  2️⃣  Test: ${YELLOW}sudo haccpro-test${NC}"
    echo -e "  3️⃣  Start: ${YELLOW}sudo systemctl start haccpro-sensor${NC}"
    echo -e "  4️⃣  Check: ${YELLOW}haccpro-status${NC}"
    echo
    echo -e "${BLUE}📚 Commands:${NC}"
    echo -e "  • Status: ${YELLOW}haccpro-status${NC}"
    echo -e "  • Logs: ${YELLOW}haccpro-logs${NC}"
    echo -e "  • Live logs: ${YELLOW}haccpro-logs -f${NC}"
    echo -e "  • System stats: ${YELLOW}sudo -u haccpro /opt/haccpro/venv/bin/python3 /opt/haccpro/sensor.py --stats${NC}"
    echo
    echo -e "${BLUE}🌐 Dashboard: ${YELLOW}https://dashboard.haccpro.nl${NC}"
    echo -e "  └─ Go to 'Apparaat Beheer' tab to see your sensor"
    echo -e "${BLUE}📊 Company: ${YELLOW}Company ID $COMPANY_ID - $COMPANY_LOCATION${NC}"
    echo -e "${BLUE}📖 Support: ${YELLOW}support@haccpro.nl${NC}"
    echo
    echo -e "${GREEN}✅ Optimized for $PI_MODEL - Ready to monitor!${NC}"
}

# Main installation function
main() {
    print_logo

    echo "🤖 Universal HACCPro sensor installer"
    echo "Automatically detects and optimizes for your Raspberry Pi model"
    echo
    
    # Company configuration - ask upfront before any system operations
    print_step "🏢 HACCPro Company Configuration"
    echo "Before installing, please configure your company settings:"
    echo

    # Check if company ID was provided via command line
    if [ -n "$COMPANY_ID" ] && [ -n "$COMPANY_LOCATION" ]; then
        # Use command line arguments
        print_info "Using command line configuration"
        print_info "Company ID: $COMPANY_ID"
        print_info "Location: $COMPANY_LOCATION"
    else
        # Try interactive mode even when piped (using /dev/tty)
        if [ -c /dev/tty ]; then
            # Interactive mode via /dev/tty - show options
            echo "Common Company IDs:"
            echo "  18 - De Pauw van Warnsveld"
            echo "  31 - [Your Company Name]"
            echo "  68 - [Your Company Name]"
            echo "  Or enter your custom company ID"
            echo
            
            while [ -z "$COMPANY_ID" ]; do
                read -p "Enter your HACCPro company ID: " COMPANY_ID < /dev/tty
                if [ -z "$COMPANY_ID" ]; then
                    print_error "Company ID cannot be empty. Please enter a valid ID."
                fi
            done
            
            while [ -z "$COMPANY_LOCATION" ]; do
                read -p "Enter your sensor location (e.g., Cold Storage, Freezer, Kitchen): " COMPANY_LOCATION < /dev/tty
                if [ -z "$COMPANY_LOCATION" ]; then
                    print_error "Location cannot be empty. Please enter a location."
                fi
            done
            echo
        else
            # Truly non-interactive - use defaults
            print_error "No interactive terminal available - using default configuration"
            print_info "Using default: Company ID 18 (De Pauw van Warnsveld)"
            print_error "💡 To specify different company: curl -sSL https://iot.haccpro.nl/sensors/install.sh | bash -s -- --company-id 31 --location 'Cold Storage'"
            COMPANY_ID="18"
            COMPANY_LOCATION="Cold Storage"
        fi
    fi

    # Show final configuration
    echo "📋 Installation Configuration:"
    print_info "Company ID: $COMPANY_ID"
    print_info "Location: $COMPANY_LOCATION"
    echo

    # Confirm before proceeding (if interactive)
    if [ -c /dev/tty ]; then
        read -p "Continue with installation? (y/N): " -r < /dev/tty
        if [[ ! $REPLY =~ ^[Yy]$ ]]; then
            print_info "Installation cancelled by user"
            exit 0
        fi
        echo
    fi

    # Run installation steps
    detect_pi_model
    check_requirements
    install_dependencies
    configure_hardware
    setup_user_and_dirs
    setup_python_environment
    create_sensor_application
    create_sensor_heartbeat
    create_systemd_service
    create_management_commands
    detect_sensors
    print_completion
}

# Check if jq is available, install if needed
if ! command -v jq &> /dev/null; then
    apt-get update -qq && apt-get install -y jq
fi

# Run main installation
main "$@"