from datetime import datetime,date
import calendar

def add_months(sourcedate, months):
    month = sourcedate.month - 1 + months
    year = sourcedate.year + month // 12
    month = month % 12 + 1
    day = min(sourcedate.day, calendar.monthrange(year,month)[1])
    return date(year, month, day)


def build_periods(period,months):
    sourcedate = datetime.strptime(f"{period}", '%Y%m')
    month = sourcedate.month - 1 + months
    year = sourcedate.year + month // 12
    month = month % 12 + 1
    day = min(sourcedate.day, calendar.monthrange(year,month)[1])
    return date(year, month, day)




period = int(date.today().strftime("%Y%m"))
grid = 3
period = 202601

#get conversion from date operations and convert to int period 
# date_string = f"{period}"
# when = datetime.strptime(f"{date_string}", "%Y%m")  # Avoids leap year bug.
# op = datetime.fromisoformat(f"{when}")
# nperiod = add_months(op,-4)

# print(f"months :: :{int(nperiod.strftime('%Y%m'))}")

#print(f"period :: :{ int( (build_periods(period,-4)).strftime('%Y%m'))}")

### start
print(f"Current Period {period}")

reel = 1
reel = 0
reel = -1

periods = []

if reel > 0 or reel < 0:
    steps = grid - 1
else :
    if grid % 2 == 1:
        steps = int((grid -1) / 2)

if reel <= 0:
    ini = int(build_periods(period, steps*-1).strftime("%Y%m"))
else:
    ini = period 

for x in range(0,grid):
    periods.append( int( build_periods(ini, x).strftime("%Y%m")) )


print(periods)

