from __future__ import annotations

import sys
from pathlib import Path

import pytest

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

import k3s_result


ATTEMPT = "a" * 24


def test_attempt_mailbox_accepts_one_digest_checked_bundle(tmp_path):
    mailbox = k3s_result.ResultMailbox("127.0.0.1", ATTEMPT, tmp_path)
    target = mailbox.start()
    source = tmp_path / "source.bundle"
    source.write_bytes(b"bounded result")
    k3s_result.upload_result(target, source)
    received = mailbox.wait(1)
    assert received.read_bytes() == b"bounded result"
    with pytest.raises(RuntimeError, match="HTTP 409"):
        k3s_result.upload_result(target, source)
    mailbox.close()
    assert not received.exists()


def test_upload_target_is_bound_to_attempt_and_ipv4():
    target = k3s_result.UploadTarget(
        f"https://127.0.0.1:24443/v1/cdx-results/{ATTEMPT}",
        "t" * 43,
        "-----BEGIN CERTIFICATE-----\nfixture\n-----END CERTIFICATE-----\n",
    )
    assert k3s_result.validate_target(target, ATTEMPT).hostname == "127.0.0.1"
    with pytest.raises(ValueError, match="does not match"):
        k3s_result.validate_target(target, "b" * 24)


def test_mailbox_refuses_oversized_declared_upload(tmp_path, monkeypatch):
    mailbox = k3s_result.ResultMailbox("127.0.0.1", ATTEMPT, tmp_path)
    target = mailbox.start()
    source = tmp_path / "too-large.bundle"
    source.write_bytes(b"x")
    monkeypatch.setattr(k3s_result, "MAX_BUNDLE_BYTES", 0)
    with pytest.raises(ValueError, match="size is invalid"):
        k3s_result.upload_result(target, source)
    mailbox.close()
