from __future__ import annotations

from fastapi.testclient import TestClient

from grantflow.api.app import app

client = TestClient(app, follow_redirects=False)


# --- No auth configured (default dev mode) ---


def test_hitl_ui_returns_200_when_no_auth_configured(monkeypatch):
    monkeypatch.delenv("GRANTFLOW_API_KEY", raising=False)
    response = client.get("/ui/hitl")
    assert response.status_code == 200
    assert "text/html" in response.headers["content-type"]
    assert "HITL Review" in response.text


def test_hitl_ui_contains_approve_and_reject_buttons(monkeypatch):
    monkeypatch.delenv("GRANTFLOW_API_KEY", raising=False)
    response = client.get("/ui/hitl")
    assert "btn-approve" in response.text
    assert "btn-reject" in response.text
    assert "hitl/pending" in response.text
    assert "hitl/approve" in response.text


def test_hitl_ui_contains_resume_logic(monkeypatch):
    monkeypatch.delenv("GRANTFLOW_API_KEY", raising=False)
    response = client.get("/ui/hitl")
    assert "resume/" in response.text


# --- Auth configured ---


def test_hitl_ui_returns_401_when_auth_configured_and_no_key(monkeypatch):
    monkeypatch.setenv("GRANTFLOW_API_KEY", "test-key-abc")
    response = client.get("/ui/hitl")
    assert response.status_code == 401
    assert "text/html" in response.headers["content-type"]
    assert "Sign in" in response.text


def test_hitl_ui_returns_401_for_wrong_key_in_query(monkeypatch):
    monkeypatch.setenv("GRANTFLOW_API_KEY", "test-key-abc")
    response = client.get("/ui/hitl?api_key=wrong-key")
    assert response.status_code == 401
    assert "Invalid" in response.text


def test_hitl_ui_redirects_and_sets_cookie_for_valid_query_key(monkeypatch):
    monkeypatch.setenv("GRANTFLOW_API_KEY", "test-key-abc")
    response = client.get("/ui/hitl?api_key=test-key-abc")
    assert response.status_code == 302
    assert response.headers["location"] == "/ui/hitl"
    assert "gf_api_key" in response.headers.get("set-cookie", "")


def test_hitl_ui_serves_page_with_valid_cookie(monkeypatch):
    monkeypatch.setenv("GRANTFLOW_API_KEY", "test-key-abc")
    authed_client = TestClient(app, follow_redirects=False, cookies={"gf_api_key": "test-key-abc"})
    response = authed_client.get("/ui/hitl")
    assert response.status_code == 200
    assert "HITL Review" in response.text


def test_hitl_ui_returns_401_with_wrong_cookie(monkeypatch):
    monkeypatch.setenv("GRANTFLOW_API_KEY", "test-key-abc")
    wrong_client = TestClient(app, follow_redirects=False, cookies={"gf_api_key": "wrong"})
    response = wrong_client.get("/ui/hitl")
    assert response.status_code == 401


def test_hitl_ui_excluded_from_openapi_schema(monkeypatch):
    monkeypatch.delenv("GRANTFLOW_API_KEY", raising=False)
    response = client.get("/openapi.json")
    assert response.status_code == 200
    paths = response.json().get("paths", {})
    assert "/ui/hitl" not in paths
