import type { BeaconPositioningProvider, BeaconReading, PositionEstimate } from './positioning';
import type { Beacon } from '../types';
import { buildBeaconMap, getBeaconKey, type MappedBeacon } from './beaconMap';
import { estimateHallwayPosition } from './hallwayEstimator';
import { RssiFilter } from './rssiFilter';
import {
  CATCH_UP_LERP_FACTOR,
  CATCH_UP_WALK_SPEED_MPS,
  POSITION_LERP_FACTOR,
  RSSI_EMA_ALPHA,
  SCAN_BATCH_GAP_MS,
  WALK_SPEED_MPS,
  advanceSmoothedPosition,
} from './smoothing';

const DEBUG_SESSION = '41be73';
const DEBUG_INGEST =
  'https://worst-copier-smitten.ngrok-free.dev/ingest/3feb8fa8-d5b1-4f19-8791-ddc034752f2c';

function agentLog(
  location: string,
  message: string,
  data: Record<string, unknown>,
  hypothesisId: string,
): void {
  // #region agent log
  fetch(DEBUG_INGEST, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-Debug-Session-Id': DEBUG_SESSION,
      'ngrok-skip-browser-warning': 'true',
    },
    body: JSON.stringify({
      sessionId: DEBUG_SESSION,
      runId: 'post-fix',
      location,
      message,
      data,
      timestamp: Date.now(),
      hypothesisId,
    }),
  }).catch(() => {});
  // #endregion
}

/**
 * A function provided by the host app (which has the actual BLE permissions
 * and native dependencies) that starts scanning for BLE beacons.
 *
 * It must call `onReading` whenever a beacon is detected, and return a
 * cleanup function that stops the scan when invoked.
 */
export type BleScannerFn = (onReading: (reading: BeaconReading) => void) => () => void;

/** Optional overrides for RSSI / visual smoothing. */
export interface BlePositioningOptions {
  rssiEmaAlpha?: number;
  lerpFactor?: number;
  catchUpLerpFactor?: number;
  scanBatchGapMs?: number;
  walkSpeedMps?: number;
  catchUpWalkSpeedMps?: number;
}

/**
 * Foundation for BLE-based indoor positioning.
 *
 * This class orchestrates incoming raw beacon readings (via an injected scanner)
 * and applies hallway-line estimation to emit X/Z/floor position estimates.
 */
export class BleBeaconProvider implements BeaconPositioningProvider {
  // A lookup map of beacon UUID -> physical location in the 3D model
  private beaconMap: Map<string, MappedBeacon>;
  private scannerFn: BleScannerFn;
  private stopScanning?: () => void;
  private rssiFilter: RssiFilter;

  private positionSubscribers = new Set<(pos: PositionEstimate) => void>();
  private readingSubscribers = new Set<(reading: BeaconReading) => void>();
  private readingBuffer = new Map<string, BeaconReading>();
  private emitTimer: ReturnType<typeof setInterval> | null = null;
  /** Keep the previous beacon long enough to interpolate while walking to the next. */
  private STALE_READING_MS = 10_000;
  /** Position emit interval. Lower = snappier blue dot; still well under BLE scan rate. */
  private EMIT_INTERVAL_MS = 150;

  /** Previous emitted position for LERP smoothing */
  private lastPosition: { x: number; z: number } | null = null;
  private lerpFactor: number;
  private catchUpLerpFactor: number;
  private scanBatchGapMs: number;
  /**
   * Brisk walking pace. The cap exists to reject non-physical motion: the
   * estimator can hop tens of metres when the strongest beacon changes.
   */
  private walkSpeedMps: number;
  private catchUpWalkSpeedMps: number;
  /** Remaining emit ticks that should use catch-up lerp after a scan dump. */
  private catchUpTicks = 0;
  /** Metres per normalised scene unit, used by the hallway estimator. */
  private metresPerUnit: number;
  private lastDebugLog = 0;
  private matchedSinceLog = 0;
  private unknownSinceLog = 0;
  private emittedSinceLog = 0;
  private cappedSinceLog = 0;
  private lerpSinceLog = 0;
  private catchUpSinceLog = 0;
  private lastEmitted: { x: number; z: number; accuracy: string } | null = null;
  private lastTarget: { x: number; z: number } | null = null;
  private lastLagUnits = 0;
  private lastMaxStep = 0;
  private lastMatchAt = 0;
  private lastRawRssi: number | null = null;
  private lastEmaRssi: number | null = null;
  private lastMatchKey: string | null = null;
  private lastLerpUsed = POSITION_LERP_FACTOR;

  /**
   * @param beacons The list of beacons fetched from the Duon API
   * @param scannerFn The platform-specific BLE scanning function
   * @param metresPerUnit Metres per normalised scene unit for this floor
   * @param options Optional RSSI / visual smoothing overrides
   */
  constructor(
    beacons: Beacon[],
    scannerFn: BleScannerFn,
    metresPerUnit = 1,
    options: BlePositioningOptions = {},
  ) {
    this.beaconMap = buildBeaconMap(beacons);
    this.scannerFn = scannerFn;
    this.metresPerUnit = Math.max(metresPerUnit, 0.01);
    this.rssiFilter = new RssiFilter(3, options.rssiEmaAlpha ?? RSSI_EMA_ALPHA);
    this.lerpFactor = options.lerpFactor ?? POSITION_LERP_FACTOR;
    this.catchUpLerpFactor = options.catchUpLerpFactor ?? CATCH_UP_LERP_FACTOR;
    this.scanBatchGapMs = options.scanBatchGapMs ?? SCAN_BATCH_GAP_MS;
    this.walkSpeedMps = options.walkSpeedMps ?? WALK_SPEED_MPS;
    this.catchUpWalkSpeedMps = options.catchUpWalkSpeedMps ?? CATCH_UP_WALK_SPEED_MPS;
    this.lastLerpUsed = this.lerpFactor;
    agentLog('BleBeaconProvider.ts:ctor', 'provider constructed', {
      cmsBeaconCount: beacons.length,
      mapSize: this.beaconMap.size,
      metresPerUnit: this.metresPerUnit,
      lerpFactor: this.lerpFactor,
      catchUpLerpFactor: this.catchUpLerpFactor,
      rssiEmaAlpha: options.rssiEmaAlpha ?? RSSI_EMA_ALPHA,
      walkMps: this.walkSpeedMps,
      emitMs: this.EMIT_INTERVAL_MS,
      keys: [...this.beaconMap.keys()].slice(0, 8),
    }, 'A');
  }

  start(): void {
    if (this.stopScanning) return; // Already scanning

    this.attachScanner();

    // The dot must glide on a clock of its own. Driving emits from the scan
    // callback ties the blue dot to the BLE packet rate, which on Android is
    // both sparse and bursty, so the dot lurches instead of moving.
    this.emitTimer = setInterval(() => this.emit(), this.EMIT_INTERVAL_MS);
  }

  /**
   * Forget the current blue-dot history and bounce the BLE scanner so the
   * next estimate snaps from live RSSI instead of crawling from a stale fix.
   */
  relocate(): void {
    this.resetEstimate();
    if (!this.stopScanning) return;
    this.stopScanning();
    this.stopScanning = undefined;
    this.attachScanner();
    agentLog('BleBeaconProvider.ts:relocate', 'manual rescan requested', {
      mapSize: this.beaconMap.size,
      emitTimer: this.emitTimer !== null,
    }, 'A');
  }

  private attachScanner(): void {
    this.stopScanning = this.scannerFn((reading) => {
      this.readingSubscribers.forEach(sub => sub(reading));

      const beaconKey = getBeaconKey(reading.uuid, reading.major, reading.minor);
      const beaconInfo = this.beaconMap.get(beaconKey);
      if (beaconInfo) {
        this.matchedSinceLog += 1;
        const now = Date.now();
        if (this.lastMatchAt > 0 && now - this.lastMatchAt >= this.scanBatchGapMs) {
          const gapMs = now - this.lastMatchAt;
          this.catchUpTicks = Math.min(
            8,
            Math.max(2, Math.ceil(gapMs / this.EMIT_INTERVAL_MS)),
          );
          this.catchUpSinceLog += 1;
        }
        const smoothedRssi = this.rssiFilter.addReading(beaconKey, reading.rssi);
        this.lastRawRssi = reading.rssi;
        this.lastEmaRssi = smoothedRssi;
        this.lastMatchKey = beaconKey;
        this.lastMatchAt = now;
        this.readingBuffer.set(beaconKey, { ...reading, rssi: smoothedRssi, timestamp: now });
      } else {
        this.unknownSinceLog += 1;
      }

      this.flushDebug(reading);
    });
  }

  private resetEstimate(): void {
    this.rssiFilter.clear();
    this.readingBuffer.clear();
    this.lastPosition = null;
    this.lastTarget = null;
    this.lastMatchKey = null;
    this.lastRawRssi = null;
    this.lastEmaRssi = null;
    this.lastMatchAt = 0;
    this.catchUpTicks = 0;
  }

  private emit(): void {
    const now = Date.now();
    this.readingBuffer.forEach((bufReading, key) => {
      if (now - (bufReading.timestamp ?? 0) > this.STALE_READING_MS) {
        this.readingBuffer.delete(key);
      }
    });

    const position = estimateHallwayPosition(
      Array.from(this.readingBuffer.values()),
      this.beaconMap,
      this.lastPosition,
      this.metresPerUnit,
    );

    if (!position) return;

    this.lastTarget = { x: position.x, z: position.z };
    const catchingUp = this.catchUpTicks > 0;
    const lerpFactor = catchingUp ? this.catchUpLerpFactor : this.lerpFactor;
    const walkMps = catchingUp ? this.catchUpWalkSpeedMps : this.walkSpeedMps;
    const maxStep = (walkMps * this.EMIT_INTERVAL_MS) / 1000 / this.metresPerUnit;
    const stepped = advanceSmoothedPosition(
      this.lastPosition,
      position,
      lerpFactor,
      maxStep,
    );
    this.lastLagUnits = this.lastPosition
      ? Math.hypot(position.x - this.lastPosition.x, position.z - this.lastPosition.z)
      : 0;
    this.lastMaxStep = maxStep;
    this.lastLerpUsed = lerpFactor;
    position.x = stepped.x;
    position.z = stepped.z;
    if (stepped.capped) this.cappedSinceLog += 1;
    if (stepped.lerped) this.lerpSinceLog += 1;
    if (catchingUp) this.catchUpTicks -= 1;

    this.lastPosition = { x: position.x, z: position.z };
    this.lastEmitted = { x: position.x, z: position.z, accuracy: position.accuracy };
    this.emittedSinceLog += 1;

    this.positionSubscribers.forEach(sub => sub(position));
  }

  private flushDebug(reading: BeaconReading): void {
    const now = Date.now();
    if (now - this.lastDebugLog < 1000) return;
    this.lastDebugLog = now;
    agentLog('BleBeaconProvider.ts:tick', 'provider 1s aggregate', {
      matched: this.matchedSinceLog,
      unknown: this.unknownSinceLog,
      emitted: this.emittedSinceLog,
      capped: this.cappedSinceLog,
      lerp: this.lerpSinceLog,
      catchUp: this.catchUpSinceLog,
      catchUpTicks: this.catchUpTicks,
      bufferSize: this.readingBuffer.size,
      bufferKeys: [...this.readingBuffer.keys()].slice(0, 6),
      x: this.lastEmitted?.x ?? null,
      z: this.lastEmitted?.z ?? null,
      targetX: this.lastTarget?.x ?? null,
      targetZ: this.lastTarget?.z ?? null,
      lagUnits: this.lastLagUnits,
      maxStep: this.lastMaxStep,
      matchAgeMs: this.lastMatchAt ? now - this.lastMatchAt : null,
      rawRssi: this.lastRawRssi,
      emaRssi: this.lastEmaRssi,
      rssiLagDb: this.lastRawRssi != null && this.lastEmaRssi != null
        ? this.lastRawRssi - this.lastEmaRssi
        : null,
      matchKey: this.lastMatchKey,
      accuracy: this.lastEmitted?.accuracy ?? null,
      lastReading: `${reading.uuid}:${reading.major}:${reading.minor}`,
      rssi: reading.rssi,
      mapSize: this.beaconMap.size,
      metresPerUnit: this.metresPerUnit,
      lerpFactor: this.lastLerpUsed,
      walkMps: this.walkSpeedMps,
      emitTimer: this.emitTimer !== null,
    }, 'A');
    this.matchedSinceLog = 0;
    this.unknownSinceLog = 0;
    this.emittedSinceLog = 0;
    this.cappedSinceLog = 0;
    this.lerpSinceLog = 0;
    this.catchUpSinceLog = 0;
  }

  stop(): void {
    if (this.emitTimer) {
      clearInterval(this.emitTimer);
      this.emitTimer = null;
    }
    if (this.stopScanning) {
      this.stopScanning();
      this.stopScanning = undefined;
      this.resetEstimate();
    }
  }

  onPosition(callback: (position: PositionEstimate) => void): () => void {
    this.positionSubscribers.add(callback);
    return () => this.positionSubscribers.delete(callback);
  }

  onBeaconReading(callback: (reading: BeaconReading) => void): () => void {
    this.readingSubscribers.add(callback);
    return () => this.readingSubscribers.delete(callback);
  }
}
