// File: App_Common.h
#ifndef _APP_COMMON_H_
#define _APP_COMMON_H_

#include "Amperometric.h"
#include "Impedance.h"
#include "RampTest.h"
#include "ad5940.h"
#include "pico/stdlib.h"
#include "rp2040port.h"
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// --- Hardware Definitions ---
#define PIN_MISO 0
#define PIN_CS 1
#define PIN_SCK 2
#define PIN_MOSI 3
#define PIN_RST 9
#define PIN_INT 29

#define APPBUFF_SIZE 512
#define AD5940ERR_STOP 10

#ifndef LPTIARF_BYPASS
#define LPTIARF_BYPASS 0x2000
#endif

// --- Application State Enums ---
typedef enum {
  MODE_IDLE,
  MODE_IMPEDANCE,
  MODE_AMPEROMETRIC,
  MODE_RAMP
} AppMode;

// --- Global Variables ---
extern uint32_t AppBuff[APPBUFF_SIZE];
extern AppMode CurrentMode;
extern float LFOSCFreq;
extern uint32_t g_AmpIndex;
extern uint32_t g_RampIndex;

// Configuration Globals
extern uint32_t ConfigLptiaVal;
extern uint32_t ConfigHstiaVal;
extern uint32_t CurrentLpTiaRf;
extern uint32_t ConfigRLoad;
extern float CalibratedLptiaVal;
extern float CalibratedHstiaVal;
extern float CalibratedHstiaPhase; // Added for single-point phase correction
extern BoolFlag GlobalShortRe0Se0;

// --- Function Prototypes ---

// From AD5940_Platform.c
void setup_pins(void);
int32_t AD5940PlatformCfg(void);
void SystemReset(void);
uint32_t GetHSTIARtia(uint32_t val);
uint32_t GetLPTIARtia(uint32_t val);
uint32_t GetLPTIARload(uint32_t val);
void ImpedanceShowResult(uint32_t *pData, uint32_t DataCount);
void AmperometricShowResult(float *pData, uint32_t DataCount);
void RampShowResult(float *pData, uint32_t DataCount);

// From Measurement_Core.c
void AD5940ImpedanceStructInit(void);
void AD5940AMPStructInit(void);
void AD5940RampStructInit(void);
void Config_LPLOOP(float bias_mv);
void Calibrate_HSDAC(float freq);
void Configure_Filters(float freq);
void Do_WaveGen(float freq);
void AD5941_InitAll(void);

// From Measurement_Routines.c
void Routine_CalibrateLFO(void);
void Routine_Measure(float freq, float bias_mv);
void Routine_Sweep(float start, float end, int steps, float bias_mv);
void Routine_Amperometric(float bias_mv);
void Routine_LSV(float start_mv, float end_mv, int steps, int duration_ms);
void Routine_CalibrateSystem(void);

#endif