from __future__ import annotations

from fastapi.testclient import TestClient

from jarvis_finance.api.main import READ_ONLY_POST_PATHS, create_app
from jarvis_finance.api.security import resolve_write_mode
from jarvis_finance.services import system_ops


def test_write_mode_defaults_fail_closed_for_remote_clients(monkeypatch) -> None:
    monkeypatch.delenv("JARVIS_FINANCE_WRITE_MODE", raising=False)
    app = create_app()
    client = TestClient(app, client=("100.64.0.10", 50000))

    assert app.state.write_mode == "disabled"
    assert client.get("/api/health").status_code == 200
    response = client.post("/api/system/restart-frontend")
    assert response.status_code == 403
    assert response.json() == {"detail": "write_operations_disabled"}


def test_unknown_write_mode_fails_closed() -> None:
    assert resolve_write_mode(environ={"JARVIS_FINANCE_WRITE_MODE": "unexpected"}) == "disabled"


def test_raiffeisen_preview_is_explicitly_read_only_in_disabled_mode() -> None:
    assert "/api/portfolio/manual-snapshot/raiffeisen/preview" in READ_ONLY_POST_PATHS


def test_local_only_mode_blocks_tailnet_and_allows_loopback(monkeypatch) -> None:
    calls: list[str] = []

    def fake_restart(action: str):
        calls.append(action)
        return {
            "status": "scheduled",
            "action": f"restart_{action}",
            "component": action,
            "started_at": "now",
            "message": "Restart geplant.",
            "worker_started": True,
            "log_available": True,
        }

    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)
    app = create_app(write_mode="local_only")

    remote = TestClient(app, client=("100.64.0.10", 50000))
    assert remote.post("/api/system/restart-frontend").status_code == 403
    assert calls == []

    loopback = TestClient(app, client=("127.0.0.1", 50000))
    assert loopback.post("/api/system/restart-frontend").status_code == 200
    assert calls == ["frontend"]


def test_test_mode_is_restricted_to_testclient_source() -> None:
    app = create_app(write_mode="test")
    remote = TestClient(app, client=("100.64.0.10", 50000))
    assert remote.post("/api/system/restart-frontend").status_code == 403


def test_runtime_status_redacts_local_paths() -> None:
    client = TestClient(create_app(write_mode="disabled"))
    payload = client.get("/api/runtime/status").json()

    assert payload["db_path"] in {"external-runtime", "blocked-inside-repo"}
    assert "/" not in payload["db_path"]
    assert "\\" not in payload["db_path"]
    assert payload["write_mode"] == "disabled"
