"""
Wachtel REMOTE connector
For Wachtel bakery ovens with REMOTE monitoring system
"""

from typing import Dict, Any
from .rest_api_connector import GenericRESTAPIConnector
from .base_connector import SensorReading, EquipmentCapabilities


class WachtelREMOTEConnector(GenericRESTAPIConnector):
    """
    Connector for Wachtel ovens via REMOTE monitoring system

    Expected configuration:
    {
        "endpoint": "https://remote.wachtel.de/api",  # Example endpoint
        "port": 443,
        "credentials": {
            "username": "bakery-username",
            "password": "bakery-password"
        },
        "additional_config": {
            "oven_id": "oven-serial-number",
            "data_endpoint": "/ovens/{oven_id}/readings",
            "status_endpoint": "/ovens/{oven_id}/status",
            "timeout": 10
        }
    }

    Note: Actual API endpoints need to be obtained from Wachtel
    Contact: support@wachtel.de or visit https://www.wachtel.de
    """

    def __init__(self, equipment_id: str, config: Dict[str, Any]):
        self.oven_id = config.get('additional_config', {}).get('oven_id', equipment_id)

        if 'additional_config' not in config:
            config['additional_config'] = {}

        config['additional_config'].setdefault(
            'data_endpoint', f'/ovens/{self.oven_id}/readings'
        )
        config['additional_config'].setdefault(
            'status_endpoint', f'/ovens/{self.oven_id}/status'
        )

        super().__init__(equipment_id, config)

    def _parse_sensor_data(self, data: Dict[str, Any]) -> SensorReading:
        """
        Parse Wachtel REMOTE API response

        Expected format (to be confirmed with actual API):
        {
            "timestamp": "2025-01-12T10:30:00Z",
            "oven_status": "baking",
            "deck_temperatures": [180, 185, 190],  # Multiple deck support
            "target_temperatures": [180, 185, 190],
            "energy_consumption_kwh": 15.2,
            "current_power_kw": 18.5,
            "operation_hours": 1245,
            ...
        }
        """
        # Parse deck temperatures (Wachtel ovens typically have multiple decks)
        deck_temps = data.get('deck_temperatures', [])
        temperature_zones = {}

        if deck_temps:
            for i, temp in enumerate(deck_temps, 1):
                temperature_zones[f'deck_{i}'] = temp

        # Primary temperature is average or first deck
        primary_temp = deck_temps[0] if deck_temps else data.get('temperature')

        # Map Wachtel status to standard status
        oven_status = data.get('oven_status', '').lower()
        operational_status = self._map_wachtel_status(oven_status)

        return SensorReading(
            timestamp=self._parse_timestamp(data.get('timestamp')),
            temperature=primary_temp,
            temperature_zones=temperature_zones if temperature_zones else None,
            target_temperature=data.get('target_temperature'),
            humidity=None,  # Wachtel deck ovens typically don't have humidity sensors
            target_humidity=None,
            energy_consumption_kwh=data.get('energy_consumption_kwh'),
            power_current_kw=data.get('current_power_kw'),
            operational_status=operational_status,
            cycle_stage=data.get('baking_program'),
            cycle_progress_percentage=data.get('cycle_progress'),
            time_remaining_minutes=data.get('time_remaining_minutes'),
            door_status=None,  # Deck ovens don't typically report door status
            steam_level=data.get('steam_injection_active'),
            additional_sensors={
                'deck_count': len(deck_temps),
                'operation_hours': data.get('operation_hours'),
                'maintenance_due': data.get('maintenance_due'),
                'deck_temperatures': deck_temps,
                'target_temperatures': data.get('target_temperatures'),
            }
        )

    def _map_wachtel_status(self, wachtel_status: str) -> str:
        """Map Wachtel-specific status to standard operational status"""
        status_map = {
            'off': 'idle',
            'standby': 'idle',
            'preheating': 'warming_up',
            'baking': 'running',
            'ready': 'idle',
            'error': 'error',
            'maintenance': 'maintenance'
        }
        return status_map.get(wachtel_status, 'unknown')

    async def get_capabilities(self) -> EquipmentCapabilities:
        """Get Wachtel oven capabilities"""
        # Try to determine number of decks from config or API
        deck_count = self.config.get('additional_config', {}).get('deck_count', 3)

        return EquipmentCapabilities(
            supports_temperature=True,
            supports_humidity=False,  # Typically not available on deck ovens
            supports_energy_monitoring=True,
            supports_remote_control=False,  # REMOTE is monitoring only
            supports_realtime=True,
            temperature_zones=deck_count,
            supported_protocols=['rest_api'],
            manufacturer_specific_features={
                'manufacturer': 'Wachtel',
                'product_line': 'Deck Ovens',
                'platform': 'REMOTE',
                'features': [
                    'multi_deck_monitoring',
                    'energy_consumption_tracking',
                    'maintenance_alerts',
                    'operation_hours_tracking',
                    'deck_specific_temperature_control'
                ]
            }
        )


# Register connector
from .base_connector import ConnectorFactory
ConnectorFactory.register_connector('wachtel_remote', WachtelREMOTEConnector)
ConnectorFactory.register_connector('wachtel', WachtelREMOTEConnector)  # Alias
