#!/usr/bin/env python3
# workdays - count working days between two dates (weekends excluded)
# Usage: workdays START END [--holidays FILE] [--list] [--include-end]
#   START/END are YYYY-MM-DD. Holidays file: one YYYY-MM-DD per line (# comments ok).
#   Example: workdays 2026-12-01 2026-12-31
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 count_workdays(start, end, holidays=frozenset(), include_end=False):
    if end < start:
        start, end = end, start
    last = end + timedelta(days=1) if include_end else end
    n, d = 0, start
    while d < last:
        if d.weekday() < 5 and d not in holidays:
            n += 1
        d += timedelta(days=1)
    return n

def selftest():
    # 2026-12-01 is a Tuesday; Dec 1-4 (Tue-Fri) = 4 workdays, Dec 5-6 weekend
    assert count_workdays(date(2026, 12, 1), date(2026, 12, 7)) == 4
    assert count_workdays(date(2026, 12, 1), date(2026, 12, 7), include_end=True) == 5  # + Mon Dec 7
    assert count_workdays(date(2026, 12, 5), date(2026, 12, 7)) == 0  # Sat-Sun
    assert count_workdays(date(2026, 12, 1), date(2026, 12, 7),
                          holidays={date(2026, 12, 2)}) == 3
    assert count_workdays(date(2026, 12, 7), date(2026, 12, 1)) == 4  # reversed ok
    print("workdays selftest: ok (weekday count, weekend exclusion, holiday, reversed)")
    return 0

def main():
    p = argparse.ArgumentParser(prog="workdays",
        description="Count working days between two dates (weekends excluded).")
    p.add_argument("start", nargs="?", help="start date YYYY-MM-DD")
    p.add_argument("end", nargs="?", help="end date YYYY-MM-DD")
    p.add_argument("--holidays", help="file with one holiday YYYY-MM-DD per line")
    p.add_argument("--list", action="store_true", help="list each working day")
    p.add_argument("--include-end", action="store_true", help="count the end date too")
    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.start or not a.end:
        p.error("START and END are required")
    try:
        start, end = parse(a.start), parse(a.end)
    except Exception as e:
        print(f"workdays: bad date: {e}", file=sys.stderr); return 2
    holidays = set()
    if a.holidays:
        try:
            for line in open(a.holidays):
                line = line.strip()
                if line and not line.startswith("#"):
                    holidays.add(parse(line))
        except OSError as e:
            print(f"workdays: {e}", file=sys.stderr); return 2
    if a.list:
        lo, hi = min(start, end), max(start, end)
        d = lo
        while d < hi or (a.include_end and d == hi):
            if d.weekday() < 5 and d not in holidays:
                print(f"{d} {d.strftime('%a')}")
            d += timedelta(days=1)
    n = count_workdays(start, end, holidays, a.include_end)
    print(f"{n} working day{'s' if n != 1 else ''} from {start} to {end}"
          + (" (end included)" if a.include_end else ""))
    return 0

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