from __future__ import annotations

"""Tests for Flask application assembly and frontend fallback behavior."""

from pathlib import Path

from atlas_portal.app_factory import create_app


def test_create_app_exposes_health_endpoint() -> None:
    app = create_app()
    client = app.test_client()

    resp = client.get("/api/healthz")

    assert resp.status_code == 200
    assert resp.get_json() == {"ok": True}


def test_create_app_returns_json_when_frontend_is_missing() -> None:
    app = create_app()
    client = app.test_client()

    original = app.static_folder
    app.static_folder = str(Path("/tmp") / "missing-frontend-dist")
    try:
        resp = client.get("/")
    finally:
        app.static_folder = original

    data = resp.get_json()
    assert resp.status_code == 200
    assert "Frontend not built yet" in data["message"]


def test_create_app_serves_existing_static_assets(tmp_path) -> None:
    app = create_app()
    (tmp_path / "index.html").write_text("<html>ok</html>")
    (tmp_path / "asset.txt").write_text("payload")
    original = app.static_folder
    app.static_folder = str(tmp_path)
    try:
        with app.test_request_context("/asset.txt"):
            resp = app.view_functions["serve_frontend"]("asset.txt")
    finally:
        app.static_folder = original

    assert resp.status_code == 200
    resp.direct_passthrough = False
    assert resp.get_data() == b"payload"
