import geopandas as gpd
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

# Load the data from the CSV
data_path = '/opt/lampp/htdocs/covid19-data-portal/Data-repository/data_repository/India/indiaactivetrans.csv'
data = pd.read_csv(data_path)

# Load the shapefile
shapefile_path = '/opt/lampp/htdocs/covid19-data-portal/India Shape File/India Shape/india_st.shp'
india_map = gpd.read_file(shapefile_path)

# Convert the 'Date' column to datetime
data['Date'] = pd.to_datetime(data['Date'])

# Sort data by State and Date
data.sort_values(by=['State', 'Date'], inplace=True)

# Calculate moving average of total active cases (7-day moving average)
data['Moving Average'] = data.groupby('State')['Total Active'].transform(lambda x: x.rolling(window=7, min_periods=1).mean())

# Calculate daily changes based on moving average
data['Daily Change'] = data.groupby('State')['Moving Average'].diff().fillna(0)

# Calculate Growth Rate: (Daily Change / Previous Moving Average) * 100
data['Growth Rate (%)'] = (data['Daily Change'] / data['Moving Average'].shift(1)) * 100
data['Growth Rate (%)'] = data['Growth Rate (%)'].where(data['Moving Average'].shift(1) > 0)

# Average the growth rates for each state, ignoring NaN values
average_growth_rate = data.groupby('State')['Growth Rate (%)'].mean().reset_index()

# Normalize state names for merging
india_map['STATE'] = india_map['STATE'].str.upper().str.strip()
average_growth_rate['State'] = average_growth_rate['State'].str.upper().str.strip()

# Merge the GeoDataFrame with the average growth rate data
india_map = india_map.merge(average_growth_rate, left_on='STATE', right_on='State', how='left')

# Define bins for growth rates
bins = np.linspace(0, 1, 11)  # Create 10 bins between 0 and 1
labels = range(len(bins) - 1)  # Create labels for the bins

# Assign each state to a bin based on its growth rate
india_map['Growth Rate Binned'] = pd.cut(india_map['Growth Rate (%)'], bins=bins, labels=labels, include_lowest=True)

# Set up a color map based on the bins
cmap = plt.get_cmap('viridis', len(bins) - 1)  # Get a colormap with the number of bins

# Plot the base map using the binned colors
base = india_map.plot(column='Growth Rate Binned', 
                      cmap=cmap, 
                      edgecolor='grey',
                      linewidth=0.5,
                      alpha=1)

# Add district names to the map
for x, y, label in zip(india_map.geometry.centroid.x, india_map.geometry.centroid.y, india_map['STATE']):
    plt.text(x, y, label, fontsize=3, ha='center', color='black')

# Set title and remove axis
plt.axis('off')

# Save the figure
plt.savefig('/opt/lampp/htdocs/covid19-data-portal/Data-repository/data_repository/India/india_map_binned.png', bbox_inches='tight', transparent=True, dpi=300)
plt.show()
