"""Sealine — sealed-box encryption round-trip tests."""

from __future__ import annotations

import pytest

from psyc.lines import seal
from psyc.result import Err, Ok


@pytest.fixture(autouse=True)
def _isolate_seal_dirs(tmp_path, monkeypatch):
    monkeypatch.setattr(seal, "KEYS_DIR", tmp_path / "keys")
    monkeypatch.setattr(seal, "SEALED_DIR", tmp_path / "sealed")


def test_seal_unseal_round_trip():
    seal.generate_recipient_keys("CERT-Test")
    plaintext = b'{"case": "evidence", "secret": true}'
    pkg = seal.seal(plaintext, ["CERT-Test"])
    assert isinstance(pkg, Ok)
    out = seal.unseal(pkg.value.package_id, "CERT-Test")
    assert isinstance(out, Ok)
    assert out.value == plaintext


def test_seal_to_unknown_recipient_errors():
    result = seal.seal(b"data", ["Nobody"])
    assert isinstance(result, Err)


def test_unseal_with_wrong_recipient_errors():
    seal.generate_recipient_keys("CERT-A")
    seal.generate_recipient_keys("CERT-B")
    pkg = seal.seal(b"data", ["CERT-A"])
    assert isinstance(pkg, Ok)
    # CERT-B has keys but is not on the package
    assert isinstance(seal.unseal(pkg.value.package_id, "CERT-B"), Err)


def test_multi_recipient_each_can_unseal():
    seal.generate_recipient_keys("CERT-Bund")
    seal.generate_recipient_keys("MISP")
    plaintext = b"shared evidence"
    pkg = seal.seal(plaintext, ["CERT-Bund", "MISP"])
    assert isinstance(pkg, Ok)
    for recipient in ("CERT-Bund", "MISP"):
        out = seal.unseal(pkg.value.package_id, recipient)
        assert isinstance(out, Ok) and out.value == plaintext


def test_plaintext_hash_recorded():
    import hashlib
    seal.generate_recipient_keys("R")
    plaintext = b"hash me"
    pkg = seal.seal(plaintext, ["R"])
    assert isinstance(pkg, Ok)
    assert pkg.value.plaintext_hash == hashlib.sha256(plaintext).hexdigest()
