from copy import deepcopy

import numpy as np

import json

import pytest

from m3m_disease.io import load_capture
from m3m_disease.quality import quality_check_capture


def test_generated_capture_passes_qc(trained_bundle):
    rgb, bands, metadata = load_capture(trained_bundle["manifests"][0])
    receipt = quality_check_capture(rgb, bands, metadata)
    assert receipt["passed"] is True
    assert receipt["interpretation"].endswith("not plant-disease confirmation.")


def test_qc_rejects_unverified_registration(trained_bundle):
    rgb, bands, metadata = load_capture(trained_bundle["manifests"][0])
    modified = deepcopy(metadata)
    modified["rgbToMultispectralRegistered"] = False
    modified["coRegistrationRmsePx"] = 1.5
    receipt = quality_check_capture(rgb, bands, modified)
    assert receipt["passed"] is False
    assert "rgb_multispectral_registration" in receipt["failures"]
    assert "co_registration_rmse" in receipt["failures"]


def test_qc_rejects_saturation_and_flat_rgb(trained_bundle):
    rgb, bands, metadata = load_capture(trained_bundle["manifests"][0])
    flat = np.ones_like(rgb)
    receipt = quality_check_capture(flat, bands, metadata)
    assert receipt["passed"] is False
    assert "saturation_fraction" in receipt["failures"]
    assert "rgb_blur_or_flat_scene" in receipt["failures"]


def test_qc_rejects_missing_metadata(trained_bundle):
    rgb, bands, _ = load_capture(trained_bundle["manifests"][0])
    receipt = quality_check_capture(rgb, bands, {})
    assert receipt["passed"] is False
    assert "metadata:captureId" in receipt["failures"]


def test_capture_loader_rejects_image_checksum_mismatch(tmp_path, trained_bundle):
    original_path = trained_bundle["manifests"][0]
    metadata = json.loads(original_path.read_text(encoding="utf-8"))
    metadata["files"] = {
        name: str((original_path.parent / relative).resolve())
        for name, relative in metadata["files"].items()
    }
    metadata["fileSha256"]["rgb"] = "0" * 64
    manifest = tmp_path / "tampered-manifest.json"
    manifest.write_text(json.dumps(metadata), encoding="utf-8")
    with pytest.raises(ValueError, match="checksum mismatch"):
        load_capture(manifest)
