# Copyright (C) 2026 NPO NT
# SPDX-License-Identifier: AGPL-3.0-only

from __future__ import annotations

import json
import tomllib
from pathlib import Path

from mika_deid import __version__
from mika_deid.legal import (
    COPYRIGHT_NOTICE,
    LICENSE_ID,
    PUBLIC_SOURCE_URL,
    legal_notice,
    license_path,
)


ROOT = Path(__file__).resolve().parents[1]


def test_agpl_and_corresponding_source_materials_are_present() -> None:
    licence = (ROOT / "LICENSE").read_text(encoding="utf-8")
    assert "GNU AFFERO GENERAL PUBLIC LICENSE" in licence
    assert "END OF TERMS AND CONDITIONS" in licence
    assert "NPO NT" in (ROOT / "AUTHORS.md").read_text(encoding="utf-8")
    assert "Corresponding Source" in (ROOT / "SOURCE_OFFER.md").read_text(encoding="utf-8")
    assert "PyMuPDF" in (ROOT / "THIRD_PARTY_NOTICES.md").read_text(encoding="utf-8")
    assert license_path() == ROOT / "LICENSE"


def test_python_sources_have_copyright_and_spdx_headers() -> None:
    for directory in (ROOT / "src" / "mika_deid", ROOT / "scripts", ROOT / "tests"):
        for path in directory.glob("*.py"):
            first_lines = path.read_text(encoding="utf-8").splitlines()[:2]
            assert first_lines == [
                "# Copyright (C) 2026 NPO NT",
                "# SPDX-License-Identifier: AGPL-3.0-only",
            ], path


def test_legal_notice_is_versioned_and_separates_code_from_patient_data() -> None:
    notice = legal_notice()
    assert __version__ == "0.2.1"
    assert COPYRIGHT_NOTICE in notice
    assert LICENSE_ID in notice
    assert PUBLIC_SOURCE_URL in notice
    assert "исходный код" in notice
    assert "медицинские документы" in notice


def test_direct_cyclonedx_sbom_is_versioned_and_parseable() -> None:
    sbom = json.loads((ROOT / "sbom" / "MIKA_DeID_v0.2.1.direct.cdx.json").read_text(encoding="utf-8"))
    assert sbom["bomFormat"] == "CycloneDX"
    assert sbom["specVersion"] == "1.5"
    assert sbom["metadata"]["component"]["version"] == __version__
    components = {component["name"] for component in sbom["components"]}
    assert {"PyMuPDF", "Pillow", "pypdf", "zxing-cpp", "Tesseract OCR"} <= components


def test_package_project_urls_are_build_backend_compatible_https() -> None:
    pyproject = tomllib.loads((ROOT / "pyproject.toml").read_text(encoding="utf-8"))
    assert pyproject["project"]["version"] == __version__
    assert pyproject["project"]["authors"] == [{"name": "NPO NT"}]
    assert all(
        value.startswith("https://") for value in pyproject["project"]["urls"].values()
    )
