import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation, PillowWriter
import json
from pathlib import Path
from scipy.signal import savgol_filter

# --- CONFIGURAÇÃO DE CAMINHOS ---
BASE_DIR = Path(__file__).parent / "Gateados 2025"
PASTA_AMOSTRA = BASE_DIR / "Amostra"
PASTA_OUTPUT_GIFS = BASE_DIR / "Gifs_SG"
PASTA_OUTPUT_GIFS.mkdir(parents=True, exist_ok=True)

# Amostra para o teste
ARQUIVO_RGP = PASTA_AMOSTRA / "Measurement016.rgp"

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

# 1. Carregar e Limpar via Algoritmo Adaptativo (Trimming)
with open(ARQUIVO_RGP, 'r') as f:
    dados = json.load(f)
y_bruto = np.array(dados['profile']['drill'])

# Detecção Adaptativa de Bordas (Sem valores fixos)
max_local = np.percentile(y_bruto, 98)
thresh_dinamico = max_local * 0.15
win_stabs = 20

idx_ini = 0
for i in range(len(y_bruto) - win_stabs):
    if np.mean(y_bruto[i:i+win_stabs]) > thresh_dinamico:
        idx_ini = i
        break

# Recorte do Lenho Real
y_lenho = y_bruto[idx_ini:]
x_lenho = np.arange(len(y_lenho)) * 0.1 # mm

# 2. Definição das Faixas Adaptativas (Quartis da Peça)
q1 = np.percentile(y_lenho, 25)
q3 = np.percentile(y_lenho, 75)

# 3. Preparar a Figura com Rótulos Técnicos
fig, ax = plt.subplots(figsize=(10, 6))

# Configuração dos Eixos conforme solicitado
ax.set_xlabel('Profundidade de Penetração (mm)', fontsize=10, fontweight='bold')
ax.set_ylabel('Resistência à Perfuração (Amplitude)', fontsize=10, fontweight='bold')
ax.set_title(f'Análise Digital de Sinais: {ARQUIVO_RGP.name}\n(Filtro Savitzky-Golay + Zonas de Densidade Adaptativas)', fontsize=11)

# Desenho das Faixas de Fundo (Baseadas na estatística da peça)
ax.axhspan(0, q1, color='red', alpha=0.08, label=f'Zona Inf. (<{q1:.1f})')
ax.axhspan(q1, q3, color='yellow', alpha=0.08, label=f'Zona Med. ({q1:.1f}-{q3:.1f})')
ax.axhspan(q3, max_local*1.1, color='green', alpha=0.08, label=f'Zona Sup. (>{q3:.1f})')

# Elementos da Animação
line_raw, = ax.plot(x_lenho, y_lenho, color='silver', alpha=0.4, label='Sinal Bruto (Lenho)')
line_sg, = ax.plot([], [], color='purple', lw=2, label='Rastro Suavizado (SG)')
rect_movel = plt.Rectangle((0, 0), 3.1, max_local*1.1, color='purple', alpha=0.1) # 3.1mm = janela 31
ax.add_patch(rect_movel)

ax.legend(loc='upper right', fontsize='small')
ax.set_xlim(0, x_lenho[-1])
ax.set_ylim(0, max_local * 1.1)

# Processamento SG prévio para animação
y_sg_render = savgol_filter(y_lenho, 31, 3)

x_hist, y_hist = [], []

def update(i):
    half = 15 # metade da janela 31
    if half <= i < len(y_sg_render) - half:
        x_hist.append(x_lenho[i])
        y_hist.append(y_sg_render[i])
        line_sg.set_data(x_hist, y_hist)
        # Move a janela de processamento
        rect_movel.set_xy((x_lenho[i - half], 0))
    return line_sg, rect_movel

# 4. Gerar o GIF
print(f"🎬 Gerando animação adaptativa com eixos rotulados...")
ani = FuncAnimation(fig, update, frames=range(0, len(y_sg_render), 3), blit=True)
nome_gif = PASTA_OUTPUT_GIFS / f"SG_Adaptativo_Labeled_{ARQUIVO_RGP.stem}.gif"
ani.save(nome_gif, writer=PillowWriter(fps=20))
plt.close()

print(f"✅ GIF gerado com sucesso em: {nome_gif}")
