import pymysql


#---DATABASE_CONNECTION---
try:
    connection = pymysql.connect(
        host='localhost',
        user='root',
        password='password',
        database='ovpn',
        cursorclass=pymysql.cursors.DictCursor
    )
    print("Connected to MySQL database")
except Exception as e:
    print(e)


# #------GETTING_ALL_COUNTRIES-------
# cursor = connection.cursor()
# cursor.execute("SELECT * FROM countries")
# countries = cursor.fetchall()

def masterData():
    cursor = connection.cursor()
    cursor.execute("""SELECT
                    country_id,
                    COUNT(country_id) AS country_count
                FROM (
                    SELECT
                        country_id,
                        ROW_NUMBER() OVER (PARTITION BY country_id ORDER BY updated_at DESC) AS row_num
                    FROM ovpn_servers
                    WHERE is_active = 1
                ) AS numbered_rows
                WHERE row_num <= 5
                GROUP BY country_id
                ORDER BY country_id ASC""")

    total_active_servers = cursor.fetchall()

    # Function to process rows for a given project and country
    def process_rows_for_country(country, total_rows, num_projects):
        for server_num in range(1, num_projects + 1):
            rows_per_project = total_rows // num_projects
            remaining_rows = total_rows % num_projects

            # Calculate limit and offset for the current project
            offset = (server_num - 1) * rows_per_project
            limit = rows_per_project + (1 if server_num <= remaining_rows else 0)

            # Print processing details for debugging or information
            print(f"Country: {country}, Project: {server_num}, Offset: {offset}, Limit: {limit}")
            # Here you would add your database query logic using the calculated offset and limit

    num_projects = 3

    # print(total_active_servers)
    for country in total_active_servers:

        countries = country['country_id']
        country_count = country['country_count']
        
        print(f"Processing {countries} with {country_count} active servers across {num_projects} projects:")
        process_rows_for_country(countries, country_count, num_projects)

if __name__ == '__main__':
    masterData()