#!/usr/bin/env python3
# calendar - month calendar with today highlighted and events read from a file
# Usage: calendar [--month M] [--year Y] [--events FILE]  (events file: YYYY-MM-DD: description)
import argparse, calendar as calmod, datetime, sys

def load_events(path):
    events = {}
    if not path:
        return events
    with open(path) as f:
        for line in f:
            line = line.strip()
            if not line or line.startswith("#"):
                continue
            date_part, _, desc = line.partition(":")
            date_part = date_part.strip()
            try:
                d = datetime.date.fromisoformat(date_part)
            except ValueError:
                continue
            events.setdefault(d, []).append(desc.strip())
    return events

def render(year, month, events=None, today=None):
    events = events or {}
    today = today or datetime.date.today()
    cal = calmod.Calendar(firstweekday=0)
    title = f"{calmod.month_name[month]} {year}"
    lines = [title.center(28), "Mo Tu We Th Fr Sa Su"]
    for week in cal.monthdayscalendar(year, month):
        cells = []
        for day in week:
            if day == 0:
                cells.append("  ")
            else:
                d = datetime.date(year, month, day)
                mark = "*" if d in events else " "
                if d == today:
                    cells.append(f"[{day:2d}]"[:2] if False else f"\x1b[7m{day:2d}\x1b[0m")
                else:
                    cells.append(f"{day:2d}{mark}"[:2] if mark == " " else f"{day:2d}*")
                    # keep width 2 for plain days, 3 handled by join below
                    cells[-1] = cells[-1][:2] if mark == " " else cells[-1]
        lines.append(" ".join(c.rjust(2) if len(c) <= 2 else c for c in cells))
    out = "\n".join(lines)
    if events:
        ev_lines = ["", "Events:"]
        for d in sorted(events):
            if d.year == year and d.month == month:
                for desc in events[d]:
                    ev_lines.append(f"  {d.isoformat()}: {desc}")
        if len(ev_lines) > 2:
            out += "\n" + "\n".join(ev_lines)
    return out

def selftest():
    import tempfile, os
    out = render(2026, 12, today=datetime.date(2026, 12, 3))
    assert "December 2026" in out and " 3" in out
    assert "Mo Tu We Th Fr Sa Su" in out
    with tempfile.NamedTemporaryFile("w", suffix=".txt", delete=False) as f:
        f.write("2026-12-25: Christmas\n2026-12-03: Demo day\n# comment\nbad line\n")
        path = f.name
    try:
        ev = load_events(path)
        assert datetime.date(2026, 12, 25) in ev
        out2 = render(2026, 12, ev, today=datetime.date(2026, 12, 3))
        assert "Christmas" in out2 and "Demo day" in out2
    finally:
        os.unlink(path)
    print(out2)
    print("calendar selftest OK")

def main():
    p = argparse.ArgumentParser(description="Month calendar with today highlighted and events read from a file.")
    p.add_argument("--month", type=int, default=None, help="month 1-12 (default: current)")
    p.add_argument("--year", type=int, default=None, help="year (default: current)")
    p.add_argument("--events", default=None, help="events file, one 'YYYY-MM-DD: description' per line")
    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
    now = datetime.date.today()
    month = a.month or now.month
    year = a.year or now.year
    if not 1 <= month <= 12:
        p.error("month must be 1-12")
    events = load_events(a.events)
    print(render(year, month, events))
    return 0

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