from __future__ import annotations

from fastapi.testclient import TestClient

from jarvis_finance.api.main import create_app
from jarvis_finance.services import system_ops


def test_system_status_endpoint_has_safe_shape() -> None:
    client = TestClient(create_app())
    response = client.get("/api/system/status")
    assert response.status_code == 200
    data = response.json()
    assert data["purpose"] == "system_ops_status_v1"
    assert "backend" in data and "frontend" in data
    assert "secret" not in str(data).lower()


def test_system_status_does_not_probe_caller_controlled_origin(monkeypatch) -> None:
    import jarvis_finance.api.routers.system as system_router

    captured: dict = {}

    def fake_status(**kwargs):
        captured.update(kwargs)
        return {
            "purpose": "system_ops_status_v1",
            "status": "ok",
            "api_url": kwargs["api_url"],
            "runtime_db_available": True,
            "runtime_outside_repo": True,
            "backend": {"status": "running", "port": None},
            "frontend": {"status": "offline", "port": None},
            "last_restart": None,
        }

    monkeypatch.setattr(system_router, "system_status", fake_status)
    client = TestClient(create_app())

    response = client.get(
        "/api/system/status",
        headers={"origin": "http://169.254.169.254"},
    )

    assert response.status_code == 200
    assert captured["frontend_url"] is None
    assert captured["frontend_reachable"] is False


def test_restart_endpoint_uses_allowed_service_action(monkeypatch) -> None:
    called: list[str] = []
    def fake_restart(action: str):
        called.append(action)
        return {"status": "ok", "action": f"restart_{action}", "started_at": "now", "message": "Restart angestoßen."}
    monkeypatch.setattr(system_ops, "restart_system_component", fake_restart)
    import jarvis_finance.api.routers.system as system_router
    monkeypatch.setattr(system_router, "restart_system_component", fake_restart)

    client = TestClient(create_app())
    response = client.post("/api/system/restart-frontend")

    assert response.status_code == 200
    assert response.json()["action"] == "restart_frontend"
    assert called == ["frontend"]
