#!/usr/bin/env python3
# timer - simple countdown timer with a message at the end
# Usage: timer 30 [--message "Tea is ready"] | timer --seconds 90
import argparse, sys, time

def parse_duration(s):
    # Accept plain seconds, or Mm / HhMmSs style: 90, 90s, 5m, 1m30s, 1h5m
    s = s.strip().lower()
    if s.isdigit():
        return int(s)
    total, num = 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 fmt(sec):
    sec = int(round(sec))
    h, rem = divmod(sec, 3600)
    m, s = divmod(rem, 60)
    return f"{h:02d}:{m:02d}:{s:02d}" if h else f"{m:02d}:{s:02d}"

def countdown(seconds, message, quiet=False, tick=1.0):
    end = time.time() + seconds
    while True:
        remaining = end - time.time()
        if remaining <= 0:
            break
        if not quiet:
            print(f"\r{fmt(remaining)} remaining", end="", flush=True)
        time.sleep(min(tick, remaining))
    if not quiet:
        print()
    print(f"\a⏰ Time's up! {message}")
    return 0

def selftest():
    assert parse_duration("90") == 90
    assert parse_duration("5m") == 300
    assert parse_duration("1m30s") == 90
    assert parse_duration("1h") == 3600
    assert parse_duration("2m5s") == 125
    assert fmt(3661) == "01:01:01" and fmt(90) == "01:30"
    t0 = time.time()
    countdown(0.2, "selftest", quiet=True, tick=0.05)
    assert time.time() - t0 < 5
    print("timer selftest OK")

def main():
    p = argparse.ArgumentParser(description="Simple countdown timer with a message at the end.")
    p.add_argument("duration", nargs="?", default=None, help="duration: seconds, or 5m / 1m30s / 1h")
    p.add_argument("--seconds", type=float, default=None, help="duration in seconds")
    p.add_argument("--message", default="Timer finished!", help="message at the end")
    p.add_argument("--quiet", action="store_true", help="only print the final message")
    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.seconds is not None:
        seconds = a.seconds
    elif a.duration is not None:
        try:
            seconds = parse_duration(a.duration)
        except ValueError as e:
            p.error(str(e))
    else:
        p.error("give a duration, e.g. 'timer 30' or 'timer 5m'")
    if seconds <= 0:
        p.error("duration must be positive")
    return countdown(seconds, a.message, a.quiet)

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