from __future__ import annotations

import copy
import hashlib
import importlib.util
import json
from pathlib import Path

import pytest

ROOT = Path(__file__).resolve().parent
SPEC = importlib.util.spec_from_file_location("task26_live_verifier", ROOT / "verify_lifecycle_seal.py")
assert SPEC and SPEC.loader
VERIFIER = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(VERIFIER)


def evidence():
    return json.loads((ROOT / "lifecycle-evidence.json").read_text())


def test_sealed_evidence_contract() -> None:
    VERIFIER.assert_evidence(evidence())


def test_rejects_wrong_candidate() -> None:
    value = copy.deepcopy(evidence())
    value["candidate_binding"]["full_candidate_digest"] = "0" * 64
    with pytest.raises(AssertionError):
        VERIFIER.assert_evidence(value)


def test_rejects_duplicate_delivery_claim() -> None:
    value = copy.deepcopy(evidence())
    value["lifecycle"]["delivery"]["delivery_ledger_rows"] = 2
    with pytest.raises(AssertionError):
        VERIFIER.assert_evidence(value)


def test_config_semantics_are_explicit_callback_only() -> None:
    config = evidence()["authorities"]["config"]["adaptive_nutrition"]
    assert config == {
        "delivery_enabled": True,
        "enabled": True,
        "activation": False,
        "delivery": False,
        "meaning": "delivery_enabled permits only an owner-approved explicit callback send; it does not enable adaptive or automatic sends",
    }


def test_attestation_is_redacted_and_byte_free() -> None:
    attestation = evidence()["manual_real_surface_attestation"]
    assert attestation["attestation_only"] is True
    assert attestation["customer_answers_included"] is False
    assert attestation["screenshot_bytes_included"] is False
    assert "screenshot_sha256" not in attestation


def test_cleanup_is_not_authorized_by_evidence_seal() -> None:
    cleanup = evidence()["cleanup_authorization_preflight"]
    assert cleanup["current_execute_authorized"] is False
    assert cleanup["status"].startswith("BLOCKED_")
    assert len(cleanup["present_blockers"]) == 7


def test_canonical_inventory_hash_algorithm() -> None:
    sample = {"schema": "x", "entries": []}
    expected = hashlib.sha256(b'{"entries":[],"schema":"x"}').hexdigest()
    assert hashlib.sha256(json.dumps(sample, sort_keys=True, separators=(",", ":")).encode()).hexdigest() == expected


def test_live_read_only_verification() -> None:
    assert VERIFIER.verify_live(evidence()) == {
        "checks": 54,
        "schema": "task26-live-lifecycle-independent-verification-v1",
        "status": "PASS",
        "mutations": 0,
    }


def test_inventory_and_root_seal() -> None:
    result = VERIFIER.verify_inventory()
    assert result["status"] == "PASS" and result["mutations"] == 0
