"""Tests for ``mgf-common bundle`` (OP-07)."""

from __future__ import annotations

import argparse
import tarfile
from typing import TYPE_CHECKING

from mgf.fed.cli._bundle import run_bundle

if TYPE_CHECKING:
    from pathlib import Path

    import pytest


def _isolated(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setenv("XDG_STATE_HOME", str(tmp_path / "state"))
    from mgf.common._identity import _set_identity

    _set_identity("bundle-test", "0.0.0")  # so sub-handlers don't warn


def test_bundle_writes_tarball_with_sections(
    tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
    _isolated(tmp_path, monkeypatch)
    out = tmp_path / "b.tar.gz"
    rc = run_bundle(argparse.Namespace(output=str(out)))
    assert rc == 0
    assert out.exists()
    with tarfile.open(out) as t:
        names = set(t.getnames())
    for member in (
        "mgf-bundle/README.txt",
        "mgf-bundle/version.json",
        "mgf-bundle/explain.txt",
        "mgf-bundle/doctor.txt",
        "mgf-bundle/logs.txt",
    ):
        assert member in names, f"missing {member}"


def test_bundle_version_section_is_valid_json(
    tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
    _isolated(tmp_path, monkeypatch)
    out = tmp_path / "b.tar.gz"
    run_bundle(argparse.Namespace(output=str(out)))
    import json

    with tarfile.open(out) as t:
        f = t.extractfile("mgf-bundle/version.json")
        assert f is not None
        payload = json.loads(f.read().decode("utf-8"))
    assert payload["name"] == "mgf-common"


def test_bundle_fail_open_on_bad_output_path(
    tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
    _isolated(tmp_path, monkeypatch)
    # Output path whose parent is a FILE → write fails → non-zero, no raise.
    f = tmp_path / "afile"
    f.write_text("x")
    rc = run_bundle(argparse.Namespace(output=str(f / "sub" / "b.tar.gz")))
    assert rc != 0
