import type { GestureEngine } from './GestureEngine'
import type { StepGraphSample, StepLogEntry, Landmark3D } from './types'

const GRAPH_HISTORY = 300

export class GestureTelemetry {
  readonly stepGraph: StepGraphSample[] = []
  readonly stepLog: StepLogEntry[] = []

  /**
   * Call each frame after engine.update() to collect telemetry samples.
   * Reads current state from the engine to build graph data.
   */
  sample(engine: GestureEngine, worldLandmarks: Landmark3D[]): void {
    const now = performance.now()

    // Step graph + log (sample whenever we have landmarks)
    if (worldLandmarks?.length >= 33) {
      const heelBaseL = engine.heelBaseL
      const heelBaseR = engine.heelBaseR
      const lt = worldLandmarks[31], rt = worldLandmarks[32]
      const baseL = heelBaseL ?? { x: lt.x, z: lt.z }
      const baseR = heelBaseR ?? { x: rt.x, z: rt.z }
      const sample: StepGraphSample = {
        time: now,
        leftX: lt.x - baseL.x,
        rightX: rt.x - baseR.x,
        leftZ: lt.z - baseL.z,
        rightZ: rt.z - baseR.z,
        activeStep: engine.activeStep,
      }
      this.stepGraph.push(sample)
      if (this.stepGraph.length > GRAPH_HISTORY) this.stepGraph.shift()

      if (heelBaseL && heelBaseR) {
        this.stepLog.push({
          t: now,
          ltX: lt.x, ltZ: lt.z, rtX: rt.x, rtZ: rt.z,
          blX: heelBaseL.x, blZ: heelBaseL.z, brX: heelBaseR.x, brZ: heelBaseR.z,
          dlX: lt.x - heelBaseL.x, dlZ: lt.z - heelBaseL.z,
          drX: rt.x - heelBaseR.x, drZ: rt.z - heelBaseR.z,
          step: engine.activeStep,
        })
      }
    }
  }
}
