from blends.ctx import ctx
from blends.models import (
    NId,
)
from blends.syntax.builders.assignment import (
    build_assignment_node,
)
from blends.syntax.builders.variable_declaration import (
    build_variable_declaration_node,
)
from blends.syntax.models import (
    SyntaxGraphArgs,
)
from blends.syntax.node_attributes import (
    STACK_GRAPH_IMPORT_MODULE_STEM,
)
from blends.utilities.text_nodes import (
    node_to_str,
)


def _find_import_binding(
    args: SyntaxGraphArgs,
    rhs_name: str,
) -> tuple[str, str] | None:
    scope_stack = args.metadata.get("scope_stack", [])
    if not scope_stack:
        return None
    parent_scope = scope_stack[-1]
    for neighbor in args.syntax_graph.successors(parent_scope):
        sg_node = args.syntax_graph.nodes[neighbor]
        if sg_node.get("label_type") != "Import":
            continue
        expression = str(sg_node.get("expression", ""))
        label_alias = sg_node.get("label_alias") or ""
        bound = str(label_alias) if label_alias else expression.split(".")[-1]
        if bound != rhs_name:
            continue
        stem = sg_node.get(STACK_GRAPH_IMPORT_MODULE_STEM)
        if stem:
            return str(stem), expression.split(".")[-1]
    return None


def reader(args: SyntaxGraphArgs) -> NId:
    graph = args.ast_graph
    n_attrs = graph.nodes[args.n_id]
    var_id = n_attrs["label_field_left"]
    val_id = n_attrs.get("label_field_right")
    type_id = n_attrs.get("label_field_type")

    if graph.nodes[var_id]["label_type"] == "identifier" or not val_id:
        var_name = node_to_str(graph, n_attrs["label_field_left"])
        var_type = None
        if type_id:
            var_type = node_to_str(graph, type_id)
        import_module_stem: str | None = None
        import_source_symbol: str | None = None
        if (
            ctx.has_feature_flag("StackGraph")
            and val_id is not None
            and graph.nodes[val_id].get("label_type") == "identifier"
        ):
            rhs_name = node_to_str(graph, val_id)
            result = _find_import_binding(args, rhs_name)
            if result is not None:
                import_module_stem, import_source_symbol = result
        return build_variable_declaration_node(
            args,
            var_name,
            var_type,
            val_id,
            import_module_stem=import_module_stem,
            import_source_symbol=import_source_symbol,
        )

    return build_assignment_node(args, var_id, val_id, type_id)
