# SPDX-License-Identifier: AGPL-3.0-only
# Copyright (c) 2026 sol pbc

import dataclasses
import tomllib
from pathlib import Path

import pytest

from solstone.think import features as features_module
from solstone.think.features import (
    FEATURES,
    Feature,
    MissingExtraError,
    install_hint,
    is_available,
    require_extra,
)


def _project_optional_dependencies() -> dict:
    root = Path(__file__).resolve().parents[1]
    data = tomllib.loads((root / "pyproject.toml").read_text(encoding="utf-8"))
    return data["project"]["optional-dependencies"]


def test_feature_is_frozen():
    feature = Feature(
        name="test",
        summary="x",
        pip_modules=("sys",),
        apt_packages=(),
        brew_packages=(),
        usage="x",
    )

    with pytest.raises(dataclasses.FrozenInstanceError):
        feature.name = "changed"


def test_features_registry_contents():
    assert "pdf" not in FEATURES
    assert "pdf-import" in FEATURES
    assert "pdf-export" in FEATURES

    for feature in FEATURES.values():
        assert isinstance(feature.name, str)
        assert isinstance(feature.summary, str)
        assert isinstance(feature.pip_modules, tuple)
        assert isinstance(feature.apt_packages, tuple)
        assert isinstance(feature.brew_packages, tuple)
        assert isinstance(feature.usage, str)
        assert feature.pip_modules


def test_pdf_import_feature_covers_worker_render_imports():
    assert {"pypdfium2", "PIL"} <= set(FEATURES["pdf-import"].pip_modules)


def test_is_available_true_for_pdf_import():
    assert is_available("pdf-import") is True


def test_is_available_false_for_missing_module(monkeypatch):
    monkeypatch.setattr(
        features_module,
        "FEATURES",
        {
            "fake": Feature(
                name="fake",
                summary="x",
                pip_modules=("definitely_not_installed_xyz",),
                apt_packages=(),
                brew_packages=(),
                usage="x",
            )
        },
    )

    assert is_available("fake") is False


def test_is_available_unknown_raises_keyerror():
    with pytest.raises(KeyError):
        is_available("nonexistent")


def test_install_hint_pdf_import_linux():
    assert install_hint("pdf-import", "linux") == "pip install 'solstone[pdf-import]'"


def test_install_hint_pdf_import_darwin():
    assert install_hint("pdf-import", "darwin") == "pip install 'solstone[pdf-import]'"


def test_install_hint_pdf_export_linux():
    assert (
        install_hint("pdf-export", "linux")
        == "pip install 'solstone[pdf-export]' and apt install libpango-1.0-0 libpangoft2-1.0-0"
    )


def test_install_hint_pdf_export_darwin():
    assert (
        install_hint("pdf-export", "darwin")
        == "pip install 'solstone[pdf-export]' and brew install pango"
    )


def test_pdf_meta_extra_membership():
    extras = _project_optional_dependencies()

    assert extras["pdf"] == [
        "solstone[pdf-import]",
        "solstone[pdf-export]",
    ]


def test_install_hint_unknown_raises_keyerror():
    with pytest.raises(KeyError):
        install_hint("nonexistent", "linux")


def test_missing_extra_error_message():
    err = MissingExtraError("pdf-import", "linux")

    assert (
        err.args[0]
        == "feature 'pdf-import' requires the [pdf-import] extra: pip install 'solstone[pdf-import]'"
    )


def test_missing_extra_error_name_attribute():
    assert MissingExtraError("pdf-import", "linux").name == "pdf-import"


def test_require_extra_succeeds_when_available():
    require_extra("pdf-import")


def test_require_extra_raises_when_missing(monkeypatch):
    monkeypatch.setattr(
        features_module,
        "FEATURES",
        {
            "fake": Feature(
                name="fake",
                summary="x",
                pip_modules=("definitely_not_installed_xyz",),
                apt_packages=(),
                brew_packages=(),
                usage="x",
            )
        },
    )

    with pytest.raises(MissingExtraError) as error:
        require_extra("fake")

    assert "pip install 'solstone[fake]'" in error.value.args[0]
