from typing import Optional

import pandas as pd
from numpy.f2py.crackfortran import true_intent_list

def foo():
    print(42)
    return 42

def get_population_of_country(df, country):
    """
    Get the summed population of all cities in a given country.
    :param df: Dataframe, must contain country and population as columns.
    :param country: string, name of the country, case-senstive
    :return: float: Final Population
    :raises: KeyError if column is missing
    """
    cities = df[df["country"] == country]
    print("cities")
    pop = cities["population"].sum()

    return pop

def get_cities_beyond_latitude(df, lat, north=True):
    """
    Get all rows where latitude is either north or south of given latitude.
    :param df:
    :param lat:   Breitengrad
    :param north: north is >= and !north <
    :return: Dataframe
    """
    if north:
        return df[df['lat'] >= lat]
    return df[df['lat'] < lat]


def get_larger_cities_north_of_city_conditions(df, city: str, **cmp_cols):
    mask = df["city"] == city
    for col_name, col_value in cmp_cols.items():
        mask &= df[col_name] == col_value
    row = df[mask]
    if len(row) > 1:
        raise ValueError(f"Search not unique. found: {row}")
    # Achtung potentiel mehr als eine Zeile
    latitude = row['lat'].iloc[0]
    population = row['population'].iloc[0]
    cities_north = get_cities_beyond_latitude(df, latitude, north=True)
    cities_north = cities_north[cities_north['population'] > population]
    return cities_north

def get_larger_cities_north_of_city(df, city: str, country: Optional[str]=None):
    if country:
        return get_larger_cities_north_of_city_conditions(
            df, city, country=country
        )
    return get_larger_cities_north_of_city_conditions(
        df, city
    )


if __name__ == "__main__":
    print("Country Population")
    world_cities = pd.read_excel("../../data/worldcities.xlsx")
    print(world_cities.columns)
    german_population = get_population_of_country(world_cities, "Germany")
    print(f"Population of Germany: {german_population}")
    narnia_population = get_population_of_country(world_cities, "Narnia")
    print(f"Population of Narnia: {narnia_population}")

    print("-"*100)
    print("North-South Population")
    # nord/süd
    north = get_cities_beyond_latitude(world_cities, 0, north=True)
    print(north["population"].sum())
    south = get_cities_beyond_latitude(world_cities, 0, north=False)
    print(south["population"].sum())
    print("-" * 100)
    print("Cities north of")
    cities_north_of_berlin = get_larger_cities_north_of_city(world_cities,
                                                      "Berlin",
                                                      "Germany")
    print(cities_north_of_berlin)
    cities = ["New York", "Istanbul"]
    for city in cities:
        northern_cities = get_larger_cities_north_of_city(world_cities,
                                                   city)
        print(f"Cities north of: {city}")
        print(northern_cities)
    try:
        northern_cities = get_larger_cities_north_of_city(world_cities,
                                                   "Rome")
        print("Error should have happened")
    except ValueError:
        print("Expected ValueError: Rome multiple times in world_cities")

    print(world_cities[world_cities["city"] == "Rome"])
    northern_cities = get_larger_cities_north_of_city_conditions(
        world_cities,
        "Rome",
        capital="primary",
    )
    print(northern_cities)
# conda install openpyxl
# 1) Wie viele Einwohner haben alle Deutschen Städte?
#                                     XYZ

# 2) Wie viele Einwohner leben auf der nördlichen/Südlichen Halbkugel

# 3) Welche Städte sind nördlich von Berlin und größer (Einwohner) als Berlin?
#                                   New-York
#                                   Istanbul
#                                     Rom

# funktion
#  -> raise
#  -> assert