import json

from m3m_disease.cli import main
from m3m_disease.io import write_json


def test_cli_validate_writes_qc_receipt(tmp_path, trained_bundle, capsys):
    output = tmp_path / "qc.json"
    assert main(["validate", "--manifest", str(trained_bundle["manifests"][0]), "--output", str(output)]) == 0
    value = json.loads(output.read_text(encoding="utf-8"))
    assert value["passed"] is True
    assert '"passed": true' in capsys.readouterr().out


def test_cli_train_evaluate_and_predict(tmp_path, trained_bundle, capsys):
    records_path = write_json(tmp_path / "records.json", {"schemaVersion": 1, "records": trained_bundle["records"]})
    training = tmp_path / "training"
    assert main(["train", "--records", str(records_path), "--output", str(training)]) == 0
    assert (training / "model.json").is_file()
    assert (training / "model-card.json").is_file()
    assert json.loads((training / "model-card.json").read_text(encoding="utf-8"))["promotionStatus"] == "RESEARCH_ONLY"
    prediction = tmp_path / "prediction.json"
    assert main([
        "predict", "--manifest", str(trained_bundle["manifests"][0]),
        "--model", str(training / "model.json"), "--output", str(prediction),
    ]) == 0
    assert json.loads(prediction.read_text(encoding="utf-8"))["status"] in {
        "REJECTED_QC", "REJECTED_OOD", "NO_FLAG", "REVIEW_REQUIRED"
    }
    capsys.readouterr()
