"""Tests for configurable parser integration through the tool API."""

from pathlib import Path

from carve.parser import TreeSitterParser
from carve.tools import _get_parser, configure_parser, project_import


class TestConfigureParser:
    """Tests for the configure_parser / _get_parser mechanism in tools."""

    def test_default_get_parser(self) -> None:
        """_get_parser returns a default TreeSitterParser when none configured."""
        import carve.tools as _tools

        old = _tools._configured_parser
        try:
            _tools._configured_parser = None
            parser = _get_parser()
            assert isinstance(parser, TreeSitterParser)
        finally:
            _tools._configured_parser = old

    def test_configure_parser_is_returned(self) -> None:
        """After configure_parser, _get_parser returns the same instance."""
        import carve.tools as _tools

        old = _tools._configured_parser
        try:
            custom = TreeSitterParser(extension_overrides={".foo": "python"})
            configure_parser(custom)
            assert _get_parser() is custom
        finally:
            _tools._configured_parser = old

    def test_project_import_uses_configured_parser(self, tmp_path: Path) -> None:
        """project_import picks up the configured parser's extension map."""
        import carve.tools as _tools

        old = _tools._configured_parser
        try:
            # Create a .djhtml file
            djhtml = tmp_path / "page.djhtml"
            djhtml.write_text("{% if x %}hi{% endif %}\n")

            # Without custom parser: .djhtml -> text
            _tools._configured_parser = None
            store = project_import(str(djhtml))
            assert store.language == "text"

            # With custom parser: .djhtml -> jinja
            custom = TreeSitterParser(extension_overrides={".djhtml": "jinja"})
            configure_parser(custom)
            store = project_import(str(djhtml))
            assert store.language == "jinja"
        finally:
            _tools._configured_parser = old
