"""Validate the actual API using an explicitly supplied test audio and reference."""
import argparse
import json
import os
import secrets
import tempfile
import time
from pathlib import Path

from fastapi.testclient import TestClient

from benchmark import words, error_rate
from service import make_app


def verify(audio: Path, reference: Path, output: Path):
    with tempfile.TemporaryDirectory(prefix="duutemdeg-check-") as data:
        os.environ["DATA_DIR"] = data
        os.environ["MAX_UPLOAD_MIB"] = "100"
        os.environ["ALLOWED_ORIGINS"] = "https://duutemdeg.test"
        token = secrets.token_urlsafe(40)
        os.environ["STT_ACCESS_TOKEN"] = token
        headers = {"Authorization": f"Bearer {token}", "Origin": "https://duutemdeg.test"}
        expected = reference.read_text(encoding="utf8").strip()
        with TestClient(make_app()) as client:
            assert client.get("/health").status_code == 401, "Route authentication failed."
            health = client.get("/health", headers=headers)
            assert health.status_code == 200 and health.json()["ready"], "Model is missing."
            assert health.headers["access-control-allow-origin"] == "https://duutemdeg.test"
            assert health.headers["cache-control"] == "no-store"
            malformed = client.post("/v1/jobs", headers=headers, files={"file": ("bad.wav", b"not audio", "audio/wav")})
            assert malformed.status_code == 415
            started = time.perf_counter()
            with audio.open("rb") as sample:
                post = client.post("/v1/jobs", headers=headers, files={"file": (audio.name, sample, "application/octet-stream")})
            assert post.status_code == 202, post.text
            path = "/v1/jobs/" + post.json()["id"]
            deadline = time.monotonic() + 600
            while True:
                reply = client.get(path, headers=headers)
                assert reply.status_code == 200
                job = reply.json()
                if job["status"] not in {"queued", "processing"}:
                    break
                if time.monotonic() > deadline:
                    raise TimeoutError("Real STT job timed out")
                time.sleep(.25)
            assert job["status"] == "done", job.get("error", "Job failed")
            assert not list((Path(data) / "uploads").glob("*.audio")), "Temporary audio not cleaned up"
            elapsed = time.perf_counter() - started
            ref, pred = words(expected), words(job["text"])
            report = {"model": "Cafet/whisper-small-mongolian", "revision": "d54c63a518d6dea7ab54a27c83d0b6b52bea3e9d",
                      "device": os.getenv("WHISPER_DEVICE", "cpu"), "computeType": os.getenv("WHISPER_COMPUTE_TYPE", "int8"),
                      "reference": expected, "transcript": job["text"], "segments": job["segments"],
                      "durationSeconds": job["duration"], "endToEndSeconds": round(elapsed, 3),
                      "wer": error_rate(ref, pred), "cer": error_rate("".join(ref), "".join(pred)),
                      "fixtureWords": len(ref), "checks": ["bearer-auth", "health", "exact-cors", "no-store",
                      "non-audio-rejection", "multipart-upload", "queue", "real-inference", "result", "temporary-audio-removal"],
                      "scope": "A single test recording. Datasets may overlap; held-out quality has not been established."}
            output.write_text(json.dumps(report, indent=2, ensure_ascii=False) + "\n", encoding="utf8")
            print(json.dumps(report, ensure_ascii=False))


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("audio", type=Path)
    parser.add_argument("reference", type=Path)
    parser.add_argument("--output", type=Path, required=True)
    args = parser.parse_args()
    verify(args.audio, args.reference, args.output)
