"""Unit mirror for ``mgf.fed.cli._explain`` (TS-01).

Covers the pure rendering/redaction helpers plus an end-to-end ``explain()``
render through an in-memory stream.
"""

from __future__ import annotations

import io

from mgf.common.cli._provenance import FieldSource

from mgf.fed.cli._explain import (
    _format_source,
    _format_value,
    _maybe_redact,
    _maybe_redact_kv,
    explain,
)


def test_maybe_redact_hides_credential_named_vars() -> None:
    assert _maybe_redact("MGF_SENTRY_DSN", "https://secret@host") == "***REDACTED***"
    assert _maybe_redact("MGF_LOG_LEVEL", "INFO") == "INFO"


def test_maybe_redact_kv_redacts_only_the_value_half() -> None:
    assert _maybe_redact_kv("MGF_PASSPHRASE=hunter2") == "MGF_PASSPHRASE=***REDACTED***"
    assert _maybe_redact_kv("MGF_LOG_LEVEL=INFO") == "MGF_LOG_LEVEL=INFO"
    assert _maybe_redact_kv("no-equals-sign") == "no-equals-sign"


def test_format_value_renders_scalars_and_collections() -> None:
    assert _format_value("x", None) == "(none)"
    assert _format_value("enabled", True) == "true"
    assert _format_value("items", []) == "[]"
    assert _format_value("items", ["a", "b"]) == "[a, b]"
    assert _format_value("passphrase", "secret") == "***REDACTED***"


def test_format_source_annotates_each_kind() -> None:
    assert _format_source(FieldSource(kind="default")) == "(default)"
    assert _format_source(FieldSource(kind="init")) == "(init)"
    assert _format_source(FieldSource(kind="env", detail="MGF_PASSPHRASE=x")).startswith(
        "(env: MGF_PASSPHRASE=***REDACTED***"
    )


def test_explain_renders_a_full_report_to_stream() -> None:
    buf = io.StringIO()
    rc = explain(app_name="demo", app_version="1.0.0", out=buf)
    out = buf.getvalue()
    assert rc == 0
    assert "active configuration for demo v1.0.0" in out
    assert "[logging]" in out
    assert "[meta]" in out
