"""The published spec must model the witness cosignature and RFC 3161 anchor —
the open standard covering its own flagship artifacts.
"""
import json
from pathlib import Path

import jsonschema
import pytest

from abom import sign
from abom.anchor import anchor_head
from abom.merkle import MerkleLog
from abom.signer import LocalSigner
from abom.witness import Witness

SCHEMA = Path(__file__).parents[2] / "spec" / "abom-0.1.schema.json"


@pytest.fixture
def schema():
    return json.loads(SCHEMA.read_text())


def test_schema_is_valid_and_defines_new_artifacts(schema):
    jsonschema.Draft202012Validator.check_schema(schema)
    assert "WitnessCosignature" in schema["$defs"]
    assert "TimestampAnchor" in schema["$defs"]
    refs = [b.get("$ref") for b in schema["oneOf"]]
    assert "#/$defs/WitnessCosignature" in refs
    assert "#/$defs/TimestampAnchor" in refs


def test_real_cosignature_validates(schema, tmp_path):
    w = Witness(LocalSigner(sign.load_or_create_key(tmp_path / "w.pem")))
    log = MerkleLog()
    log.append(b"a"); log.append(b"b")
    cosig = w.cosign(log.head().as_dict())
    jsonschema.validate(cosig, {"$ref": "#/$defs/WitnessCosignature", **schema})


def test_real_anchor_token_validates(schema):
    token = anchor_head({"tree_size": 2, "root_hash": "ab" * 32},
                        tsa_url="https://tsa.example/x", _post=lambda u, q, t: b"TOK")
    jsonschema.validate(token, {"$ref": "#/$defs/TimestampAnchor", **schema})
