import calendar from datetime import date, timedelta def get_billing_period( billing_day: int, date_: date, ) -> tuple[date, date]: # Determine the anchor month and year if date_.day >= billing_day: anchor_month = date_.month anchor_year = date_.year else: # Move to previous month if date_.month == 1: anchor_month = 12 anchor_year = date_.year - 1 else: anchor_month = date_.month - 1 anchor_year = date_.year # Calculate start date _, last_day = calendar.monthrange(anchor_year, anchor_month) start_date = date(anchor_year, anchor_month, min(billing_day, last_day)) # Calculate next month and year if anchor_month == 12: next_month = 1 next_year = anchor_year + 1 else: next_month = anchor_month + 1 next_year = anchor_year # Calculate end date _, next_last_day = calendar.monthrange(next_year, next_month) end_day = min(billing_day, next_last_day) end_date = date(next_year, next_month, end_day) - timedelta(days=1) return start_date, end_date