#!/usr/bin/env python3
# agecalc - age from a birthdate: years, days lived, next birthday
# Usage: agecalc BIRTHDATE [--date DATE] [--days]
#   BIRTHDATE is YYYY-MM-DD. --date ages as of that date (default today).
#   Example: agecalc 1990-06-15
import argparse, sys
from datetime import date, timedelta

def parse(s):
    y, m, d = (int(x) for x in s.strip().replace("/", "-").split("-"))
    return date(y, m, d)

def age_parts(born, on):
    years = on.year - born.year - ((on.month, on.day) < (born.month, born.day))
    try:
        last = born.replace(year=born.year + years)
    except ValueError:  # Feb 29 birthday in a non-leap year
        last = date(born.year + years, 2, 28)
    # handle Feb 29 birthdays on non-leap years
    months = (on.year - last.year) * 12 + (on.month - last.month)
    if on.day < last.day:
        months -= 1
    anchor_y = last.year + (last.month + months - 1) // 12
    anchor_m = (last.month + months - 1) % 12 + 1
    try:
        anchor = date(anchor_y, anchor_m, min(last.day, 28 if anchor_m == 2 else 31))
    except ValueError:
        anchor = date(anchor_y, anchor_m, 28)
    days = (on - anchor).days
    return years, months, days

def next_birthday(born, on):
    try:
        nb = born.replace(year=on.year)
    except ValueError:  # Feb 29
        nb = date(on.year, 2, 28)
    if nb < on:
        try:
            nb = born.replace(year=on.year + 1)
        except ValueError:
            nb = date(on.year + 1, 2, 28)
    return nb

def selftest():
    b = parse("2000-01-01")
    on = date(2026, 12, 3)
    y, m, d = age_parts(b, on)
    assert (y, m, d) == (26, 11, 2), (y, m, d)
    assert (on - b).days == 9833
    assert next_birthday(b, on) == date(2027, 1, 1)
    assert next_birthday(parse("1990-06-15"), date(2026, 6, 15)) == date(2026, 6, 15)
    print("agecalc selftest: ok (26y 11m 2d, 9833 days lived, next birthday)")
    return 0

def main():
    p = argparse.ArgumentParser(prog="agecalc",
        description="Age from a birthdate: years, days lived, next birthday.")
    p.add_argument("birthdate", nargs="?", help="birthdate YYYY-MM-DD")
    p.add_argument("--date", help="age as of this date (default today)")
    p.add_argument("--days", action="store_true", help="only print days lived")
    p.add_argument("--selftest", action="store_true", help="run built-in checks and exit")
    a = p.parse_args()
    if a.selftest:
        return selftest()
    if not a.birthdate:
        p.error("BIRTHDATE is required")
    try:
        born = parse(a.birthdate)
        on = parse(a.date) if a.date else date.today()
    except Exception as e:
        print(f"agecalc: bad date: {e}", file=sys.stderr); return 2
    if born > on:
        print("agecalc: birthdate is in the future", file=sys.stderr); return 2
    lived = (on - born).days
    if a.days:
        print(f"{lived} days")
        return 0
    y, m, d = age_parts(born, on)
    nb = next_birthday(born, on)
    print(f"age: {y} years, {m} months, {d} days")
    print(f"days lived: {lived}")
    print(f"next birthday: {nb} ({nb.strftime('%A')}, in {(nb - on).days} days)")
    return 0

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