"""
Hardware Control Endpoints (Development Mode Only)
"""

from fastapi import APIRouter, HTTPException
from typing import Dict, List
from loguru import logger

router = APIRouter()


@router.post("/hardware/scan")
async def start_scan():
    """Start RF scanning (Termux mode only)"""
    # TODO: Implement T-Embed scanning
    return {"status": "scanning"}


@router.get("/rtl433/status")
async def get_rtl433_status():
    """
    Get RTL_433 decoder status and availability

    Returns:
        - available: Whether RTL_433 binary is installed
        - version: RTL_433 version string
        - binary_path: Path to rtl_433 binary
        - timeout: Decode timeout in seconds
    """
    try:
        from ...matcher.rtl433_decoder import get_decoder

        decoder = get_decoder()
        available = decoder._check_rtl433_available()
        version = decoder.get_version() if available else None

        return {
            "available": available,
            "version": version,
            "binary_path": decoder.rtl433_path,
            "timeout": decoder.timeout,
            "status": "operational" if available else "unavailable"
        }
    except Exception as e:
        logger.error(f"Error checking RTL_433 status: {e}")
        return {
            "available": False,
            "version": None,
            "error": str(e),
            "status": "error"
        }


@router.get("/rtl433/protocols")
async def get_rtl433_protocols():
    """
    Get list of supported RTL_433 protocols

    Returns:
        - total: Total number of supported protocols
        - protocols: List of protocol objects with id and name
    """
    try:
        from ...matcher.rtl433_decoder import get_decoder

        decoder = get_decoder()

        if not decoder._check_rtl433_available():
            raise HTTPException(
                status_code=503,
                detail="RTL_433 is not available on this server"
            )

        protocols = decoder.get_supported_protocols()

        # Convert to list of objects
        protocol_list = [
            {"id": pid, "name": name}
            for pid, name in sorted(protocols.items())
        ]

        return {
            "total": len(protocol_list),
            "protocols": protocol_list
        }

    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Error getting RTL_433 protocols: {e}")
        raise HTTPException(
            status_code=500,
            detail=f"Failed to retrieve protocols: {str(e)}"
        )


@router.get("/rtl433/protocols/{protocol_id}")
async def get_protocol_info(protocol_id: int):
    """
    Get information about a specific RTL_433 protocol

    Args:
        protocol_id: Protocol ID number

    Returns:
        Protocol name and ID
    """
    try:
        from ...matcher.rtl433_decoder import get_decoder

        decoder = get_decoder()
        protocols = decoder.get_supported_protocols()

        if protocol_id not in protocols:
            raise HTTPException(
                status_code=404,
                detail=f"Protocol {protocol_id} not found"
            )

        return {
            "id": protocol_id,
            "name": protocols[protocol_id]
        }

    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Error getting protocol {protocol_id}: {e}")
        raise HTTPException(
            status_code=500,
            detail=f"Failed to retrieve protocol: {str(e)}"
        )
