from typing import List, Dict, Tuple
import sqlite3, csv

DB = 'restaurants.db'

# Helper function to run queries
def run_query(db: str, db_query: str, args: tuple = None) -> List[tuple]:
    """Return the results of running query db_query on database with name db.

    Optional query arguments for can be included in args.
    """
    
    con = sqlite3.connect(db)
    cur = con.cursor()
    
    if args is None: 
        cur.execute(db_query)
    else:
        cur.execute(db_query, args)

    data = cur.fetchall()
    cur.close()
    con.close()
    return data


# Fill out the function bodies below.
# You can use a combintion of SQL queries and Python code.
# But try to use more SQL than Python so you can practise it!

def avg_cost_city(db: str, city: str) -> int:
    """Return the average cost of a meal for a specified city in the
    restaurants table of database db.
    """
    # Add your code here   
    
    query = 'SELECT AVG(cost) FROM restaurants WHERE city = ? GROUP BY city'
    result = run_query(db, query, (city,))
    return result[0][0]

def max_cost_cuisines(db: str) -> List[tuple]:
    """Return the maximum cost for all cuisines in database db.
    
    >>> max_cost_cuisines(DB)
    [('American', 23), ('Arabian', 12), ('Bakery', 23)...<continues>
    """
    query = '''SELECT cuisine, MAX(cost) as cost
               FROM restaurants 
               GROUP by cuisine'''
    
    return run_query(db, query)  
    

def cuisine_max_cost(db: str) -> List[str]:
    """Return the one cuisine in a list of the restaurant with the 
    greatest cost per meal.
    If there is a tie, provide all of the cuisines with the max cost.
    
    Precondition: there is at least one restaurant in the database.
    
    >>> cuisine_max_cost(DB)
    ['Brazilian', 'Burger', 'Lebanese', 'Mexican']
    """
    query = """SELECT MAX(cost) AS max_cost, cuisine
               FROM restaurants
               GROUP BY cuisine
               ORDER BY max_cost DESC
            """
    
    # we have more work to do in Python, so let's
    # save the query result to a variable.
    result = run_query(db, query)
    
    max_cost = result[0][0]
    cuisines = []
    i = 0
    while i < len(result) and result[i][0] == max_cost:
        cuisines.append(result[i][1])
        i = i + 1
        
    return cuisines
    
    

def most_cuisine_for_city(db: str, city: str) -> List[str]:
    """Return the cuisine (in a list) that appears the greatest number of 
    times for a specified city in database db. 
    If there is a tie, put all of the cuisines in a tuple
    
    >>> most_cuisine_for_city(DB, 'Pasay City')
    ['European']
    """
    query = """SELECT COUNT(cuisine) as cuisine_count, cuisine
               FROM restaurants
               WHERE city = ?
               GROUP BY cuisine
               ORDER BY cuisine_count DESC"""

    result = run_query(db, query, (city,))

    max_count = result[0][0]
    cuisines = []
    i = 0
    while i < len(result) and result[i][0] == max_count:
        cuisines.append(result[i][1])
        i = i + 1
        
    return cuisines    



if __name__ == '__main__':
    #print(avg_cost_city(DB, 'Brasilia'))
    #print(cuisine_max_cost(DB))
    #print(most_cuisine_for_city(DB, 'Pasay City'))
    #print(max_cost_cuisines(DB))
    
    pass