import pyperclip

SNIPPETS = {
    1: "import 4333432numpy as np \nimport pandas as pd \nimport folium \nimport seaborn as sns \nimport matplotlib.pyplot as plt",
    2: """# Статистический анализ числовых колонок
    numeric_columns = df.select_dtypes(include='number').columns
    for col in numeric_columns:
        print(f"{col}:")
        print(f"  Медиана: {df[col].median():.2f}")
        print(f"  Среднее: {df[col].mean():.2f}")
        print(f"  Стандартное отклонение: {df[col].std():.2f}")
        print(f"  Асимметрия: {df[col].skew():.2f}")
        print(f"  Эксцесс: {df[col].kurtosis():.2f}")
        print(f"  Минимум: {df[col].min():.2f}")
        print(f"  Максимум: {df[col].max():.2f}")
        print()""",
    3: """from statsmodels.graphics.gofplots import qqplot
from matplotlib import pyplot
qqplot(df.step_frequency, line='s')
pyplot.show""",
    4: """from scipy.stats import shapiro
from scipy.stats import  normaltest
shapiro(df.step_frequency)""",
    5: """df['datetime'] = pd.to_datetime(df['datetime'])
df['hour'] =df['datetime'].dt.hour
df['time_of_day'] = pd.cut(df['hour'],bins = [0,6,12,18,24],labels=['Ночь','Утро','День','Вечер'],right=False)
""",
    6: """plt.figure(figsize=(15,10))
sns.heatmap(corr_matrix,annot=True)
corr_matrix = dfcor.corr()""",
    7: """lan = df['latitude'].mean()
lon = df['longitude'].mean()

m = folium.Map(location=[lan,lon],zoom_start=18)



for idx,row in df.iterrows():
    folium.CircleMarker(row[['latitude','longitude']].values,
    color='red',radius = 3, fill = True ).add_to(m)
m""",
    8: """ if 'datetime' not in df.columns or df['datetime'].isnull().all():
        df['datetime'] = pd.date_range('2026-01-01', periods=len(df), freq='1min')
    else:
        df['datetime'] = pd.to_datetime(df['datetime'], errors='coerce').fillna(
            pd.Timestamp('2026-01-01')
        )
           if 'latitude' not in df: df['latitude'] = 51.26 + np.random.normal(0, 0.01, len(df))
    if 'longitude' not in df: df['longitude'] = 10.86 + np.random.normal(0, 0.01, len(df))
    if 'speed' not in df: df['speed'] = np.random.normal(4, 1, len(df)).clip(1, 8)
    
    numeric = ['latitude', 'longitude', 'speed', 'elevation']
    avail_num = [col for col in numeric if col in df.columns]
     scaler = StandardScaler()
    knn = KNNImputer(n_neighbors=5, weights='distance')
    
    df_num = df[avail_num].fillna(0)
    df_scaled = scaler.fit_transform(df_num)
    df_filled = knn.fit_transform(df_scaled)
    df[avail_num] = scaler.inverse_transform(df_filled)
      df['step_frequency'] = np.clip(df['speed'] / 3.6 / 0.75 * 60, 60, 140)
        bins = [0, 500, 1500, 3000, float('inf')]
    labels = ['лес', 'холмы', 'горы', 'альпы']
    df['terrain_type'] = pd.cut(df['elevation'], bins=bins, labels=labels)
        """,

    9: """from sklearn import metrics
from sklearn.cluster import AgglomerativeClustering
from sklearn.cluster import KMeans
from sklearn.cluster import SpectralClustering
import scipy.cluster.hierarchy as shc
from scipy.cluster.hierarchy import dendrogram, linkage
from sklearn.metrics import silhouette_score
from sklearn.metrics import calinski_harabasz_score
from sklearn.decomposition import PCA""",
    10: """
X = df[['speed', 'elevation', 'step_frequency','temp']]
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
X_scaled=scaler.fit_transform(X)""",
    11: """import plotly.express as px
plt = px.scatter_3d(X, x='speed', y='elevation', z='step_frequency',
                 title='K-Means')""",
    12: """from sklearn.cluster import KMeans
wcss=[]
for k in range(1,11):
    Kmeans = KMeans(n_clusters=k,random_state=42)
    Kmeans.fit(X_scaled)
    wcss.append(Kmeans.inertia_)
""",
    13: """sns.lineplot(x=range(1,11), y=wcss, marker='o')""",
    14: """cluster = KMeans(n_clusters=3)
kmeans = cluster.fit_predict(X_scaled)""",
    15: """
plt.figure(figsize=(20, 15), dpi=100)
scatter=plt.scatter(X_scaled[:,0],X_scaled[:,1],c=kmeans)
plt.legend(*scatter.legend_elements(), title="Кластеры")""",
    16: """from sklearn.cluster import DBSCAN
DbscanCluster = DBSCAN(eps=0.5, min_samples=20)
dbscan = DbscanCluster.fit_predict(X_scaled)""",
    17: """from sklearn.mixture import GaussianMixture
gmm = GaussianMixture(n_components=2, random_state=0)
gmm_pred = gmm.fit_predict(X_scaled)""",
    18: """harabKmeans = metrics.calinski_harabasz_score(X_scaled, kmeans)
metrics.calinski_harabasz_score(X_scaled, kmeans)""",
    19: """silhKmeans = metrics.silhouette_score(X_scaled, kmeans)
metrics.silhouette_score(X_scaled, kmeans)""",
    20: """metrics = ['Kmeans', 'dbscan','gmm_pred']
scores = [harabKmeans, harabDBscan,harabgmm_pred]
plt.bar(metrics, scores, color=['blue', 'green'])
for i, v in enumerate(scores):
    plt.text(i, v, f'{v:.2f}', ha='center', va='bottom')""",
    21: """GEOPOINT(FLOAT([Широта]), FLOAT([Долгота]))
MARKUP(
    "ID точки: ", [ID точки], BR(),
    "Трек: ", [ID трека], BR(),
    "Время: ", [Дататайм], BR(),
    "Скорость: ", [Скорость], " км/ч", BR(),
    "Температура: ", [Температура ], "°C"
)""",
}

def s(id: int = 1) -> bool:

    text = SNIPPETS.get(id, SNIPPETS[1])
    pyperclip.copy(text)
def ClusterKMeans(id: int = 1) -> bool:

    text = SNIPPETS.get(id, SNIPPETS[1])
    pyperclip.copy(text)

def figsize(id: int = 1, id2: int = 1) -> bool:
    text = SNIPPETS.get(id, SNIPPETS[1])
    pyperclip.copy(text)

def x(id: int = 1) -> bool:

    text = SNIPPETS.get(id, SNIPPETS[1])
    pyperclip.copy(text)