import json
from pathlib import Path

import pytest
from aiohttp.test_utils import TestClient, TestServer

from relay_gateway.keys import KeyStore, hash_token
from relay_gateway.channels import build_channels
from relay_gateway.gateway import create_app


def _keyfile(tmp_path: Path, tokens: dict[str, dict]) -> Path:
    kf = tmp_path / "relay_keys.json"
    kf.write_text(
        json.dumps({hash_token(t): m for t, m in tokens.items()}), encoding="utf-8"
    )
    return kf


async def _client(tmp_path, tokens, *, tss_upstream=None) -> TestClient:
    kf = _keyfile(tmp_path, tokens)
    channels = build_channels(tmp_path, sre_upstream="http://127.0.0.1:1", tss_upstream=tss_upstream)
    app = create_app(key_store=KeyStore(kf), channels=channels)
    client = TestClient(TestServer(app))
    await client.start_server()
    return client


async def test_health_is_open(tmp_path):
    client = await _client(tmp_path, {"k": {"name": "n", "level": "all"}})
    resp = await client.get("/health")
    assert resp.status == 200
    await client.close()


async def test_missing_token_is_401(tmp_path):
    client = await _client(tmp_path, {"k": {"name": "n", "level": "sre"}})
    resp = await client.get("/api/sre/info")
    assert resp.status == 401
    await client.close()


async def test_sqb_key_denied_tss_is_403(tmp_path):
    client = await _client(tmp_path, {"k": {"name": "n", "level": "sre"}})
    resp = await client.get("/api/tss/info", headers={"Authorization": "Bearer k"})
    assert resp.status == 403
    await client.close()


async def test_tss_proxy_501_when_no_upstream(tmp_path):
    client = await _client(tmp_path, {"k": {"name": "n", "level": "tss"}})
    resp = await client.get("/api/tss/info", headers={"Authorization": "Bearer k"})
    assert resp.status == 501
    await client.close()


async def test_tss_proxy_not_501_with_upstream(tmp_path):
    client = await _client(tmp_path, {"k": {"name": "n", "level": "tss"}},
                           tss_upstream="http://127.0.0.1:6100")
    resp = await client.get("/api/tss/info", headers={"Authorization": "Bearer k"})
    assert resp.status != 501  # proxied (likely 502 no-connection in test, never 501)
    await client.close()


async def test_whoami_returns_grant(tmp_path):
    client = await _client(tmp_path, {"k": {"name": "cn", "level": "sre"}})
    resp = await client.get("/api/whoami", headers={"Authorization": "Bearer k"})
    assert resp.status == 200
    body = await resp.json()
    assert body == {"name": "cn", "level": "sre", "channels": ["sre"]}
    await client.close()


async def test_ws_rejects_bad_token(tmp_path):
    client = await _client(tmp_path, {"k": {"name": "n", "level": "tss"}})
    ws = await client.ws_connect("/ws/sre", headers={"Authorization": "Bearer k"})
    msg = await ws.receive()
    assert msg.type.name in {"CLOSE", "CLOSED", "CLOSING"}
    await client.close()
