import matplotlib.pyplot as plt
import pandas as pd
import matplotlib.ticker as mtick

def plot_total_tests_per_million(poland_csv_path, germany_csv_path, save_path):
    # Population data
    population_germany = 83.28e6  # 83.28 million
    population_poland = 36.69e6  # 36.69 million

    poland = pd.read_csv(poland_csv_path)
    poland['date'] = pd.to_datetime(poland['date'])
    germany = pd.read_csv(germany_csv_path)
    germany['date'] = pd.to_datetime(germany['date'])

    # Normalize total tests per million
    poland['total_tests_per_million'] = (poland['total_tests'] / population_poland) * 1e6
    germany['total_tests_per_million'] = (germany['total_tests'] / population_germany) * 1e6

    # Define base font size and calculate the 40% increased size
    base_font_size = plt.rcParams['font.size'] # Get default font size
    increased_font_size = base_font_size * 1.7

    fig, ax = plt.subplots(figsize=(12, 6)) 

    ax.plot(
        poland['date'],
        poland['total_tests_per_million'],
        color='blue',
        label='Poland (Tests per million)',
    )
    ax.plot(
        germany['date'],
        germany['total_tests_per_million'],
        color='orange',
        label='Germany (Tests per million)',
    )

    # Set data cutoff at the end of 2022
    cutoff_date = pd.to_datetime('2022-09-01')
    poland_truncated = poland[poland['date'] <= cutoff_date]
    germany_truncated = germany[germany['date'] <= cutoff_date]

    ax.set_xticks(
        ticks=germany_truncated['date'].iloc[::max(1, len(germany_truncated) // 10)],
        labels=germany_truncated['date'].iloc[::max(1, len(germany_truncated) // 10)].dt.strftime('%Y-%m'),
        rotation=45,
    )
    ax.tick_params(axis='x', labelsize=increased_font_size * 0.9) # Increased font size for x-axis ticks
    ax.tick_params(axis='y', labelsize=increased_font_size * 0.9) # Increased font size for y-axis ticks

    ax.set_xlabel('Date', fontsize=increased_font_size) # Increased font size
    ax.set_ylabel('Total Tests per Million', fontsize=increased_font_size) # Increased font size
    ax.set_title('Total COVID-19 Tests per Million People: Poland vs Germany', fontsize=16 * 1.4) # Increased font size
    ax.legend(fontsize=increased_font_size * 0.9) # Increased font size for legend
    ax.set_xlim(None, cutoff_date)
    plt.tight_layout()

    # Format y-axis labels in millions
    def millions(x, pos):
        return '%1.1fM' % (x * 1e-6)

    formatter = mtick.FuncFormatter(millions)
    ax.yaxis.set_major_formatter(formatter) # Apply formatter to the ax object

    plt.savefig(save_path)
    plt.show()
