from datetime import datetime, time as dt_time


def _parse_hhmm(value, fallback):
    try:
        hour, minute = str(value or "").split(":", 1)
        return dt_time(int(hour), int(minute))
    except Exception:
        return fallback


def settings():
    try:
        import config
        cfg = getattr(config, "_cfg", {}).get("quiet_time", {})
    except Exception:
        cfg = {}

    return {
        "enabled": bool(cfg.get("enabled", False)),
        "start": cfg.get("start", "23:00"),
        "end": cfg.get("end", "06:00"),
        "weather_interval_seconds": int(cfg.get("weather_interval_seconds", 3600) or 3600),
    }


def is_quiet_time(now=None):
    cfg = settings()
    if not cfg["enabled"]:
        return False

    now_time = (now or datetime.now()).time()
    start = _parse_hhmm(cfg["start"], dt_time(23, 0))
    end = _parse_hhmm(cfg["end"], dt_time(6, 0))

    if start <= end:
        return start <= now_time < end
    return now_time >= start or now_time < end


def weather_interval_seconds():
    return max(300, settings()["weather_interval_seconds"])
