#!/usr/bin/env python3
# alarm - set an alarm (sleep, then a beep and a message)
# Usage: alarm --in 10m [--message "Wake up"] | alarm --at 07:30
import argparse, datetime, sys, time

def parse_at(s, now=None):
    now = now or datetime.datetime.now()
    try:
        hh, mm = s.split(":")
        target = now.replace(hour=int(hh), minute=int(mm), second=0, microsecond=0)
    except ValueError:
        raise ValueError(f"bad time: {s!r} (use HH:MM)")
    if target <= now:
        target += datetime.timedelta(days=1)
    return target

def parse_in(s):
    s = s.strip().lower()
    if s.isdigit():
        return float(s)
    total, num = 0.0, ""
    units = {"h": 3600, "m": 60, "s": 1}
    for ch in s:
        if ch.isdigit() or ch == ".":
            num += ch
        elif ch in units and num:
            total += float(num) * units[ch]; num = ""
        else:
            raise ValueError(f"bad duration: {s!r}")
    if num:
        total += float(num)
    return total

def wait(seconds, message, quiet=False):
    if not quiet:
        print(f"Alarm set for {seconds:.0f} seconds from now. (Ctrl-C to cancel)")
    try:
        time.sleep(seconds)
    except KeyboardInterrupt:
        print("\nAlarm cancelled."); return 130
    print("\a\a\a")
    print(f"⏰ ALARM! {message} — {datetime.datetime.now().strftime('%H:%M:%S')}")
    return 0

def selftest():
    assert parse_in("10m") == 600 and parse_in("90") == 90 and parse_in("1h30m") == 5400
    now = datetime.datetime(2026, 12, 3, 10, 0, 0)
    assert parse_at("11:30", now).hour == 11
    assert parse_at("09:00", now).day == 4  # rolls to tomorrow
    t0 = time.time()
    assert wait(0.2, "selftest", quiet=True) == 0
    assert time.time() - t0 < 5
    print("alarm selftest OK")

def main():
    p = argparse.ArgumentParser(description="Set an alarm (sleep, then a beep and a message).")
    g = p.add_mutually_exclusive_group()
    g.add_argument("--at", default=None, help="alarm time HH:MM (tomorrow if already past)")
    g.add_argument("--in", dest="in_", default=None, help="alarm in DURATION, e.g. 10m, 90s, 1h")
    p.add_argument("--message", default="Wake up!", help="alarm message")
    p.add_argument("--quiet", action="store_true", help="only print the alarm itself")
    p.add_argument("--selftest", action="store_true", help="run a built-in self-test and exit")
    a = p.parse_args()
    if a.selftest:
        selftest(); return 0
    if a.at:
        try:
            target = parse_at(a.at)
        except ValueError as e:
            p.error(str(e))
        seconds = (target - datetime.datetime.now()).total_seconds()
        if not a.quiet:
            print(f"Alarm set for {target.strftime('%Y-%m-%d %H:%M')}.")
    elif a.in_:
        try:
            seconds = parse_in(a.in_)
        except ValueError as e:
            p.error(str(e))
    else:
        p.error("give --at HH:MM or --in DURATION")
    if seconds <= 0:
        p.error("alarm time must be in the future")
    return wait(seconds, a.message, a.quiet)

if __name__ == "__main__":
    sys.exit(main())
