"""
Rational ConnectedCooking API connector
For Rational iCombi ovens with ConnectedCooking cloud platform
"""

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


class RationalConnectedCookingConnector(GenericRESTAPIConnector):
    """
    Connector for Rational iCombi ovens via ConnectedCooking platform

    Expected configuration:
    {
        "endpoint": "https://www.connectedcooking.com/api/v1",
        "port": 443,
        "credentials": {
            "username": "your-email@example.com",
            "password": "your-password",
            # Or use API token if available
            "token": "your-bearer-token"
        },
        "additional_config": {
            "unit_id": "12345",  # Rational unit ID from ConnectedCooking
            "data_endpoint": "/units/{unit_id}/status",
            "status_endpoint": "/units/{unit_id}",
            "timeout": 15
        }
    }

    API Documentation: Contact Rational at cc-support@rational-online.com
    """

    def __init__(self, equipment_id: str, config: Dict[str, Any]):
        # Replace equipment_id with unit_id for Rational API
        self.unit_id = config.get('additional_config', {}).get('unit_id', equipment_id)

        # Update endpoints to use unit_id
        if 'additional_config' not in config:
            config['additional_config'] = {}

        config['additional_config'].setdefault(
            'data_endpoint', f'/units/{self.unit_id}/status'
        )
        config['additional_config'].setdefault(
            'status_endpoint', f'/units/{self.unit_id}'
        )

        super().__init__(equipment_id, config)

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

        Expected Rational ConnectedCooking response format (example):
        {
            "timestamp": "2025-01-12T10:30:00Z",
            "unit_status": "cooking",
            "cooking_mode": "combi_steam",
            "cabinet_temperature": 185.0,
            "core_temperature": 72.0,
            "humidity": 65,
            "door_open": false,
            "time_remaining_seconds": 720,
            "energy_consumption": 12.5,
            ...
        }
        """
        from datetime import datetime, timezone

        # Map Rational fields to standard SensorReading
        cabinet_temp = data.get('cabinet_temperature')
        core_temp = data.get('core_temperature')

        # Multi-zone temperature support
        temperature_zones = {}
        if cabinet_temp is not None:
            temperature_zones['cabinet'] = cabinet_temp
        if core_temp is not None:
            temperature_zones['core'] = core_temp

        # Map Rational-specific statuses
        unit_status = data.get('unit_status', '').lower()
        operational_status = self._map_rational_status(unit_status)

        # Convert time remaining from seconds to minutes
        time_remaining_seconds = data.get('time_remaining_seconds')
        time_remaining_minutes = int(time_remaining_seconds / 60) if time_remaining_seconds else None

        return SensorReading(
            timestamp=self._parse_timestamp(data.get('timestamp')),
            temperature=cabinet_temp,  # Primary temperature is cabinet
            temperature_zones=temperature_zones if temperature_zones else None,
            target_temperature=data.get('target_temperature') or data.get('cabinet_target_temperature'),
            humidity=data.get('humidity'),
            target_humidity=data.get('target_humidity'),
            energy_consumption_kwh=data.get('energy_consumption'),
            power_current_kw=data.get('current_power_kw'),
            operational_status=operational_status,
            cycle_stage=data.get('cooking_mode') or data.get('program_name'),
            cycle_progress_percentage=data.get('progress_percentage'),
            time_remaining_minutes=time_remaining_minutes,
            door_status='open' if data.get('door_open') else 'closed',
            steam_level=data.get('steam_level'),
            additional_sensors={
                'cooking_mode': data.get('cooking_mode'),
                'program_name': data.get('program_name'),
                'fan_speed': data.get('fan_speed'),
                'core_temperature': core_temp,
            }
        )

    def _map_rational_status(self, rational_status: str) -> str:
        """Map Rational-specific status to standard operational status"""
        status_map = {
            'idle': 'idle',
            'preheating': 'warming_up',
            'cooking': 'running',
            'cooling': 'cooling_down',
            'cleaning': 'maintenance',
            'error': 'error',
            'off': 'idle'
        }
        return status_map.get(rational_status, 'unknown')

    async def get_capabilities(self) -> EquipmentCapabilities:
        """Get Rational iCombi capabilities"""
        return EquipmentCapabilities(
            supports_temperature=True,
            supports_humidity=True,
            supports_energy_monitoring=True,
            supports_remote_control=True,  # ConnectedCooking supports remote operation
            supports_realtime=True,
            temperature_zones=2,  # Cabinet + Core
            supported_protocols=['rest_api'],
            manufacturer_specific_features={
                'manufacturer': 'Rational',
                'product_line': 'iCombi',
                'platform': 'ConnectedCooking',
                'features': [
                    'HACCP_documentation',
                    'recipe_management',
                    'remote_start',
                    'cooking_programs',
                    'automatic_cleaning'
                ]
            }
        )


# Register connector
from .base_connector import ConnectorFactory
ConnectorFactory.register_connector('rational_connected_cooking', RationalConnectedCookingConnector)
ConnectorFactory.register_connector('rational', RationalConnectedCookingConnector)  # Alias
