"""Tests for ECT creation and roundtrip."""

import json
import os
import time

import pytest

from ect import (
    Payload,
    create,
    generate_key,
    CreateOptions,
    verify,
    VerifyOptions,
)


def test_create_roundtrip():
    key = generate_key()
    now = int(time.time())
    payload = Payload(
        iss="spiffe://example.com/agent/a",
        aud=["spiffe://example.com/agent/b"],
        iat=now,
        exp=now + 600,
        jti="e4f5a6b7-c8d9-0123-ef01-234567890abc",
        exec_act="review_spec",
        pred=[],
    )
    compact = create(payload, key, CreateOptions(key_id="agent-a-key-1"))
    assert compact

    def resolver(kid):
        if kid == "agent-a-key-1":
            return key.public_key()
        return None

    opts = VerifyOptions(
        verifier_id="spiffe://example.com/agent/b",
        resolve_key=resolver,
        now=now,
    )
    parsed = verify(compact, opts)
    assert parsed.payload.jti == payload.jti
    assert parsed.payload.exec_act == payload.exec_act


def test_create_with_test_vector():
    path = os.path.join(os.path.dirname(__file__), "..", "testdata", "valid_root_ect_payload.json")
    if not os.path.exists(path):
        pytest.skip(f"test vector not found: {path}")
    with open(path) as f:
        data = json.load(f)
    payload = Payload.from_claims(data)
    key = generate_key()
    now = int(time.time())
    payload.iat = now
    payload.exp = now + 600

    compact = create(payload, key, CreateOptions(key_id="test-kid"))
    assert compact

    def resolver(kid):
        if kid == "test-kid":
            return key.public_key()
        return None

    opts = VerifyOptions(
        verifier_id=payload.aud[0],
        resolve_key=resolver,
        now=now,
    )
    verify(compact, opts)
