"""
System management API endpoints.
"""

import logging
from typing import List, Dict, Any

from fastapi import APIRouter, HTTPException
from pydantic import BaseModel

from ...safety.safety_monitor import safety_monitor
from ...safety.error_handler import error_handler

logger = logging.getLogger(__name__)

router = APIRouter()


class AlarmResponse(BaseModel):
    """Alarm response model."""
    id: str
    title: str
    message: str
    category: str
    priority: str
    state: str
    timestamp: str
    occurrence_count: int = 1


class SystemInfoResponse(BaseModel):
    """System information response."""
    name: str
    version: str
    environment: str
    uptime_seconds: float
    active_alarms: int
    error_count: int


@router.get("/info", response_model=SystemInfoResponse)
async def get_system_info():
    """Get system information."""
    try:
        alarm_summary = safety_monitor.get_alarm_summary()
        error_stats = error_handler.get_error_statistics()
        
        return SystemInfoResponse(
            name="Chocolate Tempering Machine",
            version="1.0.0",
            environment="development",
            uptime_seconds=0.0,  # Would calculate actual uptime
            active_alarms=alarm_summary["total_active_alarms"],
            error_count=error_stats["active_errors"]
        )
        
    except Exception as e:
        logger.error(f"Failed to get system info: {e}")
        raise HTTPException(status_code=500, detail="Failed to get system information")


@router.get("/alarms", response_model=List[AlarmResponse])
async def get_alarms(priority: Optional[str] = None):
    """Get active alarms."""
    try:
        # Filter by priority if specified
        priority_filter = None
        if priority:
            from ...safety.safety_monitor import AlarmPriority
            try:
                priority_filter = AlarmPriority(priority.upper())
            except ValueError:
                raise HTTPException(status_code=400, detail=f"Invalid priority: {priority}")
        
        alarms = safety_monitor.get_active_alarms(priority_filter)
        
        return [
            AlarmResponse(
                id=alarm.id,
                title=alarm.title,
                message=alarm.message,
                category=alarm.category.value,
                priority=alarm.priority.value,
                state=alarm.state.value,
                timestamp=alarm.timestamp.isoformat(),
                occurrence_count=alarm.occurrence_count
            )
            for alarm in alarms
        ]
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Failed to get alarms: {e}")
        raise HTTPException(status_code=500, detail="Failed to retrieve alarms")


@router.post("/alarms/{alarm_id}/acknowledge")
async def acknowledge_alarm(alarm_id: str, user: str = "system"):
    """Acknowledge an alarm."""
    try:
        success = await safety_monitor.acknowledge_alarm(alarm_id, user)
        
        return {
            "success": success,
            "message": f"Alarm {alarm_id} acknowledged" if success else f"Failed to acknowledge alarm {alarm_id}"
        }
        
    except Exception as e:
        logger.error(f"Failed to acknowledge alarm {alarm_id}: {e}")
        raise HTTPException(status_code=500, detail="Failed to acknowledge alarm")


@router.get("/errors")
async def get_active_errors():
    """Get active system errors."""
    try:
        errors = error_handler.get_active_errors()
        
        return {
            "active_errors": [
                {
                    "error_id": error.error_id,
                    "component": error.component,
                    "function_name": error.function_name,
                    "timestamp": error.timestamp.isoformat(),
                    "exception": str(error.exception),
                    "retry_count": error.retry_count,
                }
                for error in errors
            ],
            "statistics": error_handler.get_error_statistics()
        }
        
    except Exception as e:
        logger.error(f"Failed to get active errors: {e}")
        raise HTTPException(status_code=500, detail="Failed to retrieve active errors")


@router.get("/configuration")
async def get_system_configuration():
    """Get system configuration."""
    try:
        from ....shared.config import settings
        
        return {
            "environment": settings.environment,
            "debug": settings.debug,
            "log_level": settings.log_level.value,
            "app_name": settings.app_name,
            "app_version": settings.app_version,
            "api_version": settings.web.api_version,
            "host": settings.web.host,
            "port": settings.web.port,
        }
        
    except Exception as e:
        logger.error(f"Failed to get system configuration: {e}")
        raise HTTPException(status_code=500, detail="Failed to retrieve system configuration")