from __future__ import annotations

import math
import os
import sys
import time

import numpy as np

PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if PROJECT_ROOT not in sys.path:
    sys.path.insert(0, PROJECT_ROOT)

from services.vad import VADService


def main() -> None:
    vad = VADService()
    sr = 16000
    chunk = 512

    # 1s silence -> 1s speech-like sine -> 1s silence
    t = np.arange(sr, dtype=np.float32) / sr
    speech = 0.20 * np.sin(2 * math.pi * 220 * t).astype(np.float32)
    seq = [np.zeros(sr, dtype=np.float32), speech, np.zeros(sr, dtype=np.float32)]
    stream = np.concatenate(seq)

    starts = 0
    ends = 0
    first_start_ms = -1
    t0 = time.perf_counter()
    for i in range(0, stream.shape[0] - chunk + 1, chunk):
        evt = vad.push_chunk(stream[i : i + chunk])
        if evt and "start" in evt:
            starts += 1
            if first_start_ms < 0:
                first_start_ms = int((time.perf_counter() - t0) * 1000)
        if evt and "end" in evt:
            ends += 1

    print("vad.health:", vad.health)
    print("vad.starts:", starts, "vad.ends:", ends, "first_start_ms:", first_start_ms)
    if starts < 1 or ends < 1:
        raise SystemExit("vad check failed: start/end not detected")
    print("vad check: ok")


if __name__ == "__main__":
    main()
