import json
import math

def average_in_period(year, month = None):
    """
    Returns the average flow recorded in given month of given year (or total year) as long as year in data range.
    """
    
    try:
        with open(f'flow_{year}.json') as f:
            data = json.load(f)
            if month:
                total = 0
                count = 0
                for reading in data["data"]:
                    if int(reading["measured_at"].split("-")[1]) == int(month):
                        total += float(reading["value"])
                        count += 1
                return round(total / count, 1) if count else 0
            else:
                total = 0
                for reading in data["data"]:
                    total += float(reading["value"])
                return round(total / len(data["data"]), 1)
    except FileNotFoundError:
        return f'{year} not in range or invalid input'

def deviation_in_period(year, month = None):
    """
    Returns the standard deviation of the flow recorded in given month of given year (or total year) as long as year in data range.
    """
    try:
        with open(f'flow_{year}.json') as f:
            data = json.load(f)
            if month:
                total = 0
                total_sq = 0
                count = 0
                for reading in data["data"]:
                    if int(reading["measured_at"].split("-")[1]) == int(month):
                        total += float(reading["value"])
                        total_sq += (float(reading["value"])) ** 2
                        count += 1
                average = total / count if count else 0
                return  (round(average, 1), round(math.sqrt(total_sq / count - (average ** 2)), 1)) if count else (0, 0)
            else:
                total = 0
                total_sq = 0
                for reading in data["data"]:
                    total += float(reading["value"])
                    total_sq += (float(reading["value"])) ** 2
                average = total / len(data["data"])
                return round(average, 1), round(math.sqrt(total_sq / len(data["data"]) - (average ** 2)), 1)      
    except FileNotFoundError:
        return f'{year} not in range or invalid input'


