from __future__ import annotations

import json

from fastapi.testclient import TestClient

from jarvis_gateway.main import create_app
from jarvis_gateway.services.overview_service import OverviewService


def test_overview_stable_when_autoshorts_fails(monkeypatch) -> None:
    monkeypatch.setenv("AUTOSHORTS_ADAPTER_MODE", "live_readonly")
    monkeypatch.setenv("AUTOSHORTS_API_BASE_URL", "http://127.0.0.1:9")
    overview = OverviewService.from_config().build_overview()
    module = next(m for m in overview.modules if m.module_id == "autoshorts")
    assert module.status == "degraded"
    assert len(module.kpis) <= 3
    text = json.dumps(overview.model_dump(mode="json"), sort_keys=True).lower()
    for forbidden in ["token", "oauth", ".mp4", ".png", "/home/"]:
        assert forbidden not in text


def test_api_overview_stable_for_autoshorts_local_probe_missing(monkeypatch) -> None:
    monkeypatch.setenv("AUTOSHORTS_ADAPTER_MODE", "local_probe")
    monkeypatch.delenv("AUTOSHORTS_RUNTIME_BASE", raising=False)
    client = TestClient(create_app())
    response = client.get("/api/overview")
    assert response.status_code == 200
    module = next(m for m in response.json()["modules"] if m["module_id"] == "autoshorts")
    assert module["status"] in {"degraded", "offline"}
    assert module["source_health"]["source_type"] == "local_probe"


def test_modules_endpoint_reports_autoshorts_modes_without_runtime_path(monkeypatch, tmp_path) -> None:
    monkeypatch.setenv("AUTOSHORTS_ADAPTER_MODE", "local_probe")
    monkeypatch.setenv("AUTOSHORTS_RUNTIME_BASE", str(tmp_path))
    client = TestClient(create_app())
    response = client.get("/api/modules")
    assert response.status_code == 200
    assert str(tmp_path) not in response.text
    module = next(m for m in response.json() if m["module_id"] == "autoshorts")
    assert module["source_type"] == "local_probe"
    assert module["runtime_base_env"] == "AUTOSHORTS_RUNTIME_BASE"
