import logging
from pathlib import Path

from blends.ast.build_graph import get_ast_graph_from_content
from blends.models import Content, Graph, Language, NId

LOGGER = logging.getLogger(__name__)

LANGUAGE_MAP: dict[str, Language] = {
    "python": Language.PYTHON,
    "swift": Language.SWIFT,
}


def node_str(graph: Graph, n_id: NId, key: str) -> str:
    value: str = graph.nodes[n_id][key]  # type: ignore[misc]
    return value


def maybe_node_str(graph: Graph, n_id: NId, key: str) -> str | None:
    value: str | None = graph.nodes[n_id].get(key)  # type: ignore[misc]
    return value


def node_nid(graph: Graph, n_id: NId, key: str) -> NId:
    value: NId = graph.nodes[n_id][key]  # type: ignore[misc]
    return value


def maybe_node_nid(graph: Graph, n_id: NId, key: str) -> NId | None:
    value: NId | None = graph.nodes[n_id].get(key)  # type: ignore[misc]
    return value


def parse_ast_graph(content: bytes, language: str) -> Graph | None:
    blends_language = LANGUAGE_MAP.get(language)
    if not blends_language:
        LOGGER.warning("Unable to parse content for language %s", language)
        return None

    blends_content = Content(
        content_bytes=content,
        content_str=content.decode("latin-1"),
        language=blends_language,
        path=Path(),
    )
    return get_ast_graph_from_content(blends_content)
