import httpx
import pytest
from wsgiref.validate import validator

from passenger_wsgi import application

CHART = {
    "birth_date": "1990-01-01", "birth_time": "10:30",
    "timezone": "Asia/Kathmandu", "latitude": 27.7172, "longitude": 85.324,
}


@pytest.fixture
def client(monkeypatch):
    monkeypatch.setenv("CALCULATOR_TOKEN", "test-only-secret")
    transport = httpx.WSGITransport(app=validator(application), script_name="/calculator")
    with httpx.Client(transport=transport, base_url="http://test") as client:
        yield client


def test_passenger_calculator_flow(client):
    assert client.get("/health").json()["configured"]
    assert client.post("/v1/charts", json=CHART).status_code == 401
    client.headers["Authorization"] = "Bearer test-only-secret"
    response = client.post("/v1/charts", json=CHART)
    assert response.status_code == 200
    result = response.json()
    assert len(result["planets"]) == 9 and result["dashas"]
    assert client.post("/v1/charts", json={**CHART, "latitude": 100}).status_code == 422
    assert client.post("/v1/transits", json=CHART).json()["kind"] == "transit"
    assert client.post("/v1/calendar/convert", json={
        "calendar": "ad", "date": "1990-01-01",
    }).json()["gregorian"] == "1990-01-01"
    report = client.post("/v1/reports", json={
        "profile": {**CHART, "name": "नमुना", "place": "Kathmandu", "language": "ne"},
        "chart": result,
    })
    assert report.status_code == 200
    assert report.headers["cache-control"] == "no-store"
    assert report.content.startswith(b"%PDF-")


def test_passenger_rejects_oversized_body(client):
    response = client.post(
        "/v1/charts",
        content=b"{}",
        headers={
            "Authorization": "Bearer test-only-secret",
            "Content-Type": "application/json",
            "Content-Length": str(2 * 1024 * 1024 + 1),
        },
    )
    assert response.status_code == 413
