"""``apiprobe bundle`` — diagnostic tarball (OP-07).

Produces a single attachable artefact: system info + the redacted effective configuration +
captured ``doctor`` output. The one file an operator or agent can attach to a bug report.
"""

from __future__ import annotations

import contextlib
import io
import json
import platform
import tarfile
from pathlib import Path

from mgf.common.observability import Redactor

from mgf.apiprobe._version import __version__
from mgf.apiprobe.cli.doctor import handle_doctor
from mgf.apiprobe.config import ApiprobeSettings


def _add(tar: tarfile.TarFile, name: str, text: str) -> None:
    data = text.encode("utf-8")
    info = tarfile.TarInfo(name)
    info.size = len(data)
    tar.addfile(info, io.BytesIO(data))


def handle_bundle(*, out: str | None = None) -> int:
    """Write a single ``.tar.gz`` of system info + redacted config + doctor output."""
    config = ApiprobeSettings().model_dump(mode="json")
    Redactor().redact(config)
    system = {
        "apiprobe": __version__,
        "python": platform.python_version(),
        "platform": platform.platform(),
    }
    doctor_buf = io.StringIO()
    with contextlib.redirect_stdout(doctor_buf):
        handle_doctor()

    dest = Path(out) if out is not None else Path("apiprobe-diagnostic-bundle.tar.gz")
    with tarfile.open(dest, "w:gz") as tar:
        _add(tar, "system.json", json.dumps(system, indent=2))
        _add(tar, "config.json", json.dumps(config, indent=2))
        _add(tar, "doctor.txt", doctor_buf.getvalue())
    print(f"wrote diagnostic bundle: {dest}  (system + redacted config + doctor)")
    return 0
