import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation, PillowWriter
import json
import pandas as pd
from pathlib import Path

# --- AJUSTE DE CAMINHOS ---
CWD = Path.cwd()
if (CWD / "Amostra").exists():
    PASTA_AMOSTRA = CWD / "Amostra"
else:
    PASTA_AMOSTRA = CWD / "Gateados 2025" / "Amostra"

ARQUIVO_RGP = PASTA_AMOSTRA / "Measurement016.rgp"

if not ARQUIVO_RGP.exists():
    print(f"Erro: Arquivo {ARQUIVO_RGP.name} não encontrado.")
    exit()

# 1. Carregar Dados
with open(ARQUIVO_RGP, 'r') as f:
    dados = json.load(f)

# Pegamos um trecho para a animação (600 pontos)
y_bruto = np.array(dados['profile']['drill'])[:600]
x = np.arange(len(y_bruto)) * 0.1 # Escala em mm

# 2. Configurações da Janela
window_len = 31

# 3. Preparar a Figura
fig, ax = plt.subplots(figsize=(10, 6))
ax.set_xlim(0, x[-1])
ax.set_ylim(min(y_bruto)-5, max(y_bruto)+5)

# Linhas conforme a lógica SMA
line_raw, = ax.plot(x, y_bruto, color='silver', alpha=0.4, label='Sinal Bruto')
line_sma, = ax.plot([], [], color='orange', lw=2.5, label='Suavizado (Média Simples)')
line_mean, = ax.plot([], [], color='black', lw=2, label='Média da Janela')

# Janela Móvel (Retângulo)
rect = plt.Rectangle((0, 0), window_len*0.1, 100, color='orange', alpha=0.1)
ax.add_patch(rect)

ax.set_title(f'Processamento Média Móvel Simples (SMA): {ARQUIVO_RGP.name}', fontsize=12)
ax.set_xlabel('Profundidade (mm)')
ax.set_ylabel('Resistência')
ax.legend(loc='upper right')

y_sma_list = []
x_sma_list = []

def update(i):
    half = window_len // 2
    if i < half or i > len(y_bruto) - half:
        return line_sma, line_mean, rect

    # Define a janela atual
    start = i - half
    end = i + half
    window_x = x[start:end]
    window_y = y_bruto[start:end]

    # Cálculo da Média Simples (SMA)
    current_mean = np.mean(window_y)

    y_sma_list.append(current_mean)
    x_sma_list.append(x[i])

    # Atualiza o gráfico
    # A 'line_mean' mostra uma linha horizontal no nível da média atual
    line_mean.set_data(window_x, [current_mean] * len(window_x))
    line_sma.set_data(x_sma_list, y_sma_list)
    rect.set_xy((window_x[0], ax.get_ylim()[0]))

    return line_sma, line_mean, rect

# 4. Gerar o GIF
print("Iniciando renderização da animação SMA...")
ani = FuncAnimation(fig, update, frames=range(len(y_bruto)), interval=30, blit=True)

caminho_gif = Path.cwd() / "processamento_SMA_amostra.gif"
ani.save(caminho_gif, writer=PillowWriter(fps=30))

print(f"Sucesso! GIF SMA salvo como: {caminho_gif}")
plt.close()
