import json
import os
from pathlib import Path

import pytest

from web_sentinel.license.generators.key_manager import generate_key_pair
from web_sentinel.license.generators.license_generator import build_licence
from web_sentinel.license.license_manager import LicenceManager, LicenceError
from web_sentinel.license.license_validator import LicenceValidator


@pytest.fixture()
def licence_file(tmp_path):
    key_pair = generate_key_pair()
    private_path = tmp_path / "private.pem"
    private_path.write_bytes(key_pair.private_key_pem)

    config = {
        "licenseId": "TEST-001",
        "superAdmin": {"email": "admin@example.com"},
        "subscription": {
            "tier": "PRO",
            "maxUsers": 10,
            "maxDomains": 100,
            "validUntil": "2099-12-31T23:59:59Z",
            "features": ["invasive_tests", "api_access"],
        },
        "encryption": {"dbKeySeed": "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"},
    }

    licence = build_licence(config, private_path)
    licence_path = tmp_path / "license.lic"
    licence_path.write_text(json.dumps(licence.payload), encoding="utf-8")
    return licence_path


def test_licence_manager_load(licence_file, monkeypatch):
    monkeypatch.setattr(
        "web_sentinel.license.embedded_keys.LICENCE_PUBLIC_KEY",
        licence_file.read_text().split("\nsignature")[0].encode("utf-8"),
        raising=False,
    )


def test_validator_rejects_missing_file(tmp_path):
    validator = LicenceValidator(tmp_path / "missing.lic")
    with pytest.raises(LicenceError):
        validator.refresh()
