"""Tests for /api/config (2026-05-12).

Frontend uses this to construct ttyd iframe URLs without a build-time env var.
"""
from __future__ import annotations

import importlib
import os

import pytest
from fastapi.testclient import TestClient


@pytest.fixture
def client():
    """Reimport main.py so module-level env reads pick up monkeypatching."""
    import recoil.api.main as main_mod

    importlib.reload(main_mod)
    with TestClient(main_mod.app) as c:
        yield c


def test_config_returns_null_ttyd_host_when_env_unset(monkeypatch, client):
    """Unset → null so the frontend uses `window.location.hostname`.

    Returning `"localhost"` would mislead the browser into trying to load
    ttyd from the user's own machine instead of the server's address.
    """
    monkeypatch.delenv("TTYD_HOST", raising=False)
    r = client.get("/api/config")
    assert r.status_code == 200
    body = r.json()
    assert body["schemaVersion"] == 1
    assert body["ttydHost"] is None


def test_config_treats_empty_string_as_unset(monkeypatch):
    """Defensive: TTYD_HOST=\"\" behaves like unset (null) — not literal ""."""
    monkeypatch.setenv("TTYD_HOST", "   ")
    import recoil.api.main as main_mod

    importlib.reload(main_mod)
    with TestClient(main_mod.app) as c:
        r = c.get("/api/config")
    assert r.json()["ttydHost"] is None


def test_config_returns_env_ttyd_host_when_set(monkeypatch):
    """When TTYD_HOST is set, /api/config surfaces it.

    Used by the MacBook dev pair: local FastAPI sets TTYD_HOST to Studio's
    Tailscale IP so the frontend points the chat iframe at Studio.
    """
    monkeypatch.setenv("TTYD_HOST", "100.105.59.118")
    import recoil.api.main as main_mod

    importlib.reload(main_mod)
    with TestClient(main_mod.app) as c:
        r = c.get("/api/config")
    assert r.status_code == 200
    assert r.json()["ttydHost"] == "100.105.59.118"
