"""/grade endpoint + the VENDORING DRIFT GUARD (#39).

engines/grade.py is a vendored copy of tools/foundry/engine/grade.py (the
container has no Foundry). This locks the endpoint contract AND mechanically
proves the copy still grades IDENTICALLY to the canonical — so a future edit to
the Foundry grader that isn't re-vendored fails CI here, not silently in prod.

    cd armada/api && ~/.virtualenvs/douanier/bin/python -m pytest tests/test_grade_endpoint.py -q
"""
import importlib.util
import io
from pathlib import Path

import numpy as np
import pytest
import soundfile as sf
from fastapi.testclient import TestClient

import app as APP
import config
from engines import grade as vendored

client = TestClient(APP.app)
GW = {"X-Tenant": "hexa", "X-Scopes": "api:audio:*"}


def _wav_bytes(freqs=(110, 220), secs=1.5, sr=44100):
    t = np.linspace(0, secs, int(sr * secs), endpoint=False)
    y = (0.3 * sum(np.sin(2 * np.pi * f * t) for f in freqs) / len(freqs)).astype("float32")
    buf = io.BytesIO()
    sf.write(buf, y, sr, format="WAV")
    return buf.getvalue()


def test_grade_endpoint_and_cache():
    files = {"file": ("loop.wav", _wav_bytes(), "audio/wav")}
    r1 = client.post("/grade", files=files, headers=GW)
    assert r1.status_code == 200
    assert r1.headers["X-Douanier-Cache"] == "miss"
    g = r1.json()["grade"]
    assert g["tier"] in {"S", "A", "B", "C", "D"}
    assert 0.0 <= g["grade"] <= 1.0
    assert "seam" in g["sub"] and "rms_dbfs" in g["metrics"]

    r2 = client.post("/grade", files={"file": ("loop.wav", _wav_bytes(), "audio/wav")}, headers=GW)
    assert r2.headers["X-Douanier-Cache"] == "hit"


def test_grade_scope_enforced():
    # api:audio:features doesn't cover /grade → 403 (path-derived scope).
    r = client.post("/grade", files={"file": ("c.wav", _wav_bytes(), "audio/wav")},
                    headers={"X-Tenant": "hexa", "X-Scopes": "api:audio:features"})
    assert r.status_code == 403


def _load_foundry_grade():
    """Import the canonical Foundry grade.py standalone (it has no sibling imports)."""
    p = Path(config.FOUNDRY) / "engine" / "grade.py"
    if not p.exists():
        return None
    spec = importlib.util.spec_from_file_location("_foundry_grade", p)
    mod = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(mod)
    return mod


def test_vendored_copy_has_not_drifted():
    canonical = _load_foundry_grade()
    if canonical is None:
        pytest.skip("Foundry not on disk — drift guard runs in-repo only")
    sr = 44100
    rng = np.random.default_rng(0)
    t = np.linspace(0, 2.0, sr * 2, endpoint=False)
    y = (0.3 * np.sin(2 * np.pi * 110 * t) + 0.02 * rng.standard_normal(t.size)).astype("float64")

    gv = vendored.grade_array(y, sr)
    gc = canonical.grade_array(y, sr)
    assert gv.grade == gc.grade, "vendored grade.py drifted from the Foundry canonical — re-vendor"
    assert gv.tier == gc.tier
    assert gv.sub == gc.sub
    # the tunables must match too (weights/thresholds are where drift usually hides)
    assert vendored.WEIGHTS == canonical.WEIGHTS
    assert vendored.THRESH == canonical.THRESH
