"""Redaction over the cron wrapper's outputs (SPEC-P4 §5): the pager summary +
heartbeat payload carry NO secret value (canary absent), even against a poisoned
finding evidence dict.
"""

from __future__ import annotations

import json

from mgf.secrets.context import Context
from mgf.secrets.doctor import DoctorReport, Finding, Unverifiable
from mgf.secrets.watch import CodebergIssuePager, OOHeartbeat, run_watch, summarize
from tests._fakes import FakeWoodpecker

CANARY = "s3cr3t-canary-DO-NOT-LEAK-9f8e7d"  # a test fixture, never a real value


def _poisoned_report() -> DoctorReport:
    # AG-18 guarantees the doctor never puts a value in a finding; we PLANT one in the
    # evidence anyway and prove the wrapper's outputs still never carry it.
    f = Finding(
        "api_key", "C1", "high", "declared org secret 'api_key' is MISSING", {"leak": CANARY}
    )
    u = Unverifiable("C5", "forge-deploy-key:repo-x", "forge HTTP 429")
    return DoctorReport(surfaces=["woodpecker", "forge"], findings=[f], unverifiable=[u])


def test_summary_never_serialises_evidence_values() -> None:
    title, body = summarize(_poisoned_report())
    assert CANARY not in body and CANARY not in title


def test_pager_and_heartbeat_outputs_are_value_free() -> None:
    captured: list[tuple[str, str, str]] = []

    def http(method, url, headers, body):
        captured.append((method, url, body.decode("utf-8") if body else ""))
        return 200, "[]"  # GET open-issues -> none, so report() creates

    pager = CodebergIssuePager(token="pager-token", http=http)
    hb = OOHeartbeat(
        url="https://oo.example/api/default/backup_heartbeats/_json", token="hb", http=http
    )
    run_watch(_poisoned_report(), pager=pager, heartbeat=hb)

    for _method, url, sent_body in captured:
        assert CANARY not in url
        assert CANARY not in sent_body
    # And the auth token is header-only — never in any request BODY.
    assert all("pager-token" not in sent_body for _m, _u, sent_body in captured)


def test_cli_watch_no_page_runs_value_free(capsys, tmp_path) -> None:
    """The `watch` verb end-to-end (no network): --no-page + absent heartbeat files ->
    pager/heartbeat unconfigured, output is the value-free summary."""
    from mgf.secrets.cli import main
    from mgf.secrets.registry import load

    reg_text = (
        "[api_key]\nfamily='mgf'\nkind='api-token'\npurpose='p'\nconsumers=['c']\n"
        "recovery='r'\nstate='active'\n"
        "policy={allowed_repos='*', blast_radius='b'}\n"
        "rotation={class='token', staged=true}\nverify={probe='auth'}\n"
        "surfaces=[{type='woodpecker-org-secret', events=['push']}]\n"
    )
    (tmp_path / "SECRETS.toml").write_text(reg_text, encoding="utf-8")
    reg = load([tmp_path / "SECRETS.toml"])
    # A missing declared secret -> a C1 finding, so the watch has something to summarise.
    ctx = Context(fed_root=tmp_path, woodpecker=FakeWoodpecker(org_secrets={}, repos=[]))
    code = main(
        ["watch", "--surface", "woodpecker", "--config-source", "local", "--no-page", "--json"],
        registry=reg,
        context=ctx,
    )
    out = json.loads(capsys.readouterr().out)
    assert code == 1  # findings present
    assert out["pager_configured"] is False and out["heartbeat_configured"] is False
    assert out["pager_action"] == "suppressed"
    assert CANARY not in json.dumps(out)
