import os
import logging

from homeassistant.components.http import HomeAssistantView
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import UnknownFlow

from .const import DOMAIN, DEVICES_DIR, DATA_DIR

_LOGGER = logging.getLogger(__name__)

PLATFORMS = ["sensor", "switch", "text"]


class QRScanView(HomeAssistantView):
    """Receive QR scan result from scanner page and advance the config flow."""

    url = "/api/sms4iot/scan/{flow_id}"
    name = "api:sms4iot:scan"
    requires_auth = True

    async def post(self, request, flow_id):
        hass = request.app["hass"]
        try:
            data = await request.json()

        except Exception:
            return self.json_message("Invalid JSON", status_code=400)

        try:
            result = await hass.config_entries.flow.async_configure(
                flow_id, user_input=data
            )
        except UnknownFlow:
            return self.json_message("Flow not found", status_code=404)
        except Exception as err:
            _LOGGER.exception("Error advancing config flow %s", flow_id)
            return self.json_message(str(err), status_code=400)

        result_type = result["type"]
        if hasattr(result_type, "value"):
            result_type = result_type.value

        payload: dict = {"type": result_type}
        _LOGGER.warning("__init__.py result:" + result_type + " title:" + result.get("title", ""))
        payload["title"] = result.get("title", "")
        if result_type == "create_entry":
            payload["title"] = result.get("title", "")
        elif result_type == "abort":
            payload["reason"] = result.get("reason", "unknown")

        return self.json(payload)


async def async_setup(hass: HomeAssistant, config: dict) -> bool:
    hass.data.setdefault(DOMAIN, {})

    hass.http.register_static_path(
        "/sms4iot_static",
        hass.config.path("custom_components/sms4iot/frontend"),
        cache_headers=False,
    )
    hass.http.register_view(QRScanView())

    # Ensure working directories exist
    for rel_dir in [DEVICES_DIR, DATA_DIR]:
        abs_dir = hass.config.path(rel_dir)
        os.makedirs(abs_dir, exist_ok=True)

    return True


async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    from .coordinator import SmS4IoTCoordinator

    coordinator = SmS4IoTCoordinator(hass, entry)
    await coordinator.async_config_entry_first_refresh()

    hass.data[DOMAIN][entry.entry_id] = coordinator
    await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
    return True


async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
    if unload_ok:
        hass.data[DOMAIN].pop(entry.entry_id)
    return unload_ok


async def async_remove_entry(hass: HomeAssistant, entry: ConfigEntry) -> None:
    """Delete the device file when the config entry is removed."""
    device_id = entry.data["device_id"]
    device_file = hass.config.path(DEVICES_DIR, device_id)

    def _remove():
        try:
            os.remove(device_file)
            _LOGGER.debug("Removed device file %s", device_file)
        except FileNotFoundError:
            pass

    await hass.async_add_executor_job(_remove)
