import numpy as np
import json
import matplotlib.pyplot as plt
from pathlib import Path
from scipy.signal import savgol_filter

# --- CONFIGURAÇÕES DE CAMINHOS ---
BASE_DIR = Path(__file__).parent / "Gateados 2025"
PASTA_AMOSTRAS = BASE_DIR / "Amostra"

# --- ESCOLHA O EXAME ---
REGISTRO_PARA_PLOTAR = 17

def plotar_perfil_completo(registro):
    nome_arq = f"Measurement{str(int(registro)).zfill(3)}.rgp"
    caminho = PASTA_AMOSTRAS / nome_arq

    if not caminho.exists():
        print(f"Erro: Arquivo {nome_arq} não encontrado.")
        return

    with open(caminho, 'r', encoding='utf-8') as f:
        dados = json.load(f)

    # Dados Totais
    drill = np.array(dados['profile']['drill'])
    x = np.arange(len(drill))

    # Ajuste dos filtros para a escala completa
    # Aumentei levemente a janela (window_length) para que o gráfico macro não fique poluído
    drill_sg = savgol_filter(drill, window_length=51, polyorder=3)
    deriv_sg = savgol_filter(drill, window_length=101, polyorder=3, deriv=1)

    fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(16, 10), sharex=True)

    # --- GRÁFICO 1: PERFIL COMPLETO DE RESISTÊNCIA ---
    ax1.plot(x, drill, color='gray', alpha=0.15, label='Sinal Bruto', linewidth=0.5)
    ax1.plot(x, drill_sg, color='#2980b9', linewidth=1.5, label='Perfil Suavizado (SG)')

    ax1.set_title(f'Perfil Longitudinal Completo - Registro {registro}', fontsize=14, fontweight='bold')
    ax1.set_ylabel('Resistência (RP)')

    # Grid milimetrado denso para a peça completa
    ax1.grid(True, which='major', linestyle='-', alpha=0.4)
    ax1.grid(True, which='minor', linestyle=':', alpha=0.1)
    ax1.minorticks_on()
    ax1.legend(loc='upper right')

    # --- GRÁFICO 2: MONITOR DE TRANSIÇÃO (ANÉIS DE CRESCIMENTO) ---
    ax2.fill_between(x, 0, deriv_sg, where=(deriv_sg >= 0),
                     color='#27ae60', alpha=0.6, label='Lenho Tardio (Transição)')
    ax2.fill_between(x, 0, deriv_sg, where=(deriv_sg < 0),
                     color='#c0392b', alpha=0.6, label='Lenho Inicial (Transição)')

    ax2.set_title('Mapeamento Anatômico (Taxa de Variação)', fontsize=12)
    ax2.set_xlabel('Profundidade da Perfuração (Pontos)')
    ax2.set_ylabel('Δ Resistência')

    # Referências
    ax2.axhline(0, color='black', linewidth=1)
    ax2.grid(True, which='major', linestyle='-', alpha=0.4)
    ax2.minorticks_on()
    ax2.legend(loc='upper right')

    plt.tight_layout()
    print(f"Gerando visualização completa da peça: {nome_arq}")
    print(f"Total de pontos processados: {len(drill)}")
    plt.show()

if __name__ == "__main__":
    plotar_perfil_completo(REGISTRO_PARA_PLOTAR)
