from __future__ import annotations

from typing import TYPE_CHECKING

import tree_sitter_go as tsgo
from tree_sitter import Language

from vibelexity.circular_deps.models import ImportInfo
from vibelexity.circular_deps.parsers.base import ImportParser
from vibelexity.parsers.shared import parse_with_language

if TYPE_CHECKING:
    from tree_sitter import Node

GO_LANGUAGE = Language(tsgo.language())


def parse(code: str) -> Node:
    return parse_with_language(GO_LANGUAGE, code)


class GoImportParser(ImportParser):
    def extract_imports(self, source: str, filepath: str) -> list[ImportInfo]:
        root = parse(source)
        imports: list[ImportInfo] = []

        for node in root.children:
            if node.type == "import_declaration":
                for child in node.children:
                    if child.type == "import_spec":
                        imports.extend(self._process_import_spec(child))
                    elif child.type == "import_spec_list":
                        for spec in child.children:
                            if spec.type == "import_spec":
                                imports.extend(self._process_import_spec(spec))

        return imports

    def _process_import_spec(self, node: Node) -> list[ImportInfo]:
        imports: list[ImportInfo] = []
        path = ""

        for child in node.children:
            if child.type == "interpreted_string_literal":
                text = child.text.decode() if child.text else ""
                path = text.strip('"')

        if path:
            imports.append(
                ImportInfo(
                    raw_module=path,
                    resolved_path=None,
                    import_type="absolute",
                    line=node.start_point[0] + 1,
                    is_dynamic=False,
                    node_type="import_spec",
                )
            )

        return imports
