"""Read DS18B20 devices from Linux 1-Wire sysfs."""

from __future__ import annotations

from pathlib import Path

DEFAULT_DEVICES_PATH = Path("/sys/bus/w1/devices")


def c_to_f(temp_c: float) -> float:
    return temp_c * 9.0 / 5.0 + 32.0


def find_devices(devices_path: Path) -> list[str]:
    if not devices_path.exists():
        return []
    return sorted(p.name for p in devices_path.iterdir() if p.name.startswith("28-"))


def read_temp_c(devices_path: Path, device_id: str) -> float | None:
    """Return temperature in Celsius, or None if the read/parse fails."""
    slave_file = devices_path / device_id / "w1_slave"
    try:
        text = slave_file.read_text()
    except OSError:
        return None

    lines = text.strip().splitlines()
    if len(lines) < 2 or "YES" not in lines[0]:
        return None

    marker = "t="
    if marker not in lines[1]:
        return None

    try:
        milli_c = int(lines[1].split(marker, 1)[1])
    except ValueError:
        return None

    if milli_c == 85000:
        return None

    return milli_c / 1000.0


def read_all_f(devices_path: Path) -> dict[str, float | None]:
    """Return device_id -> °F (or None on failure)."""
    out: dict[str, float | None] = {}
    for device_id in find_devices(devices_path):
        temp_c = read_temp_c(devices_path, device_id)
        out[device_id] = None if temp_c is None else c_to_f(temp_c)
    return out
