//! Go import declaration processing — emits Imports edges and builds
//! the alias map used by the call resolver.

use ckg_core::{Edge, EdgeKind};
use tree_sitter::Node;

use crate::util::text;
use super::Ctx;

pub(crate) fn handle_imports(ctx: &mut Ctx<'_>, n: Node<'_>, src: &str) {
    // `import "x"` (single) or `import (… )` (block of import_specs).
    let mut stack = vec![n];
    while let Some(node) = stack.pop() {
        if node.kind() == "import_spec" {
            let mut alias: Option<String> = None;
            let mut path: Option<String> = None;
            let mut c = node.walk();
            for ch in node.children(&mut c) {
                match ch.kind() {
                    "package_identifier" | "blank_identifier" | "dot" => {
                        alias = Some(text(ch, src).to_string());
                    }
                    "interpreted_string_literal" | "raw_string_literal" => {
                        // Find the inner content child if present, else strip quotes.
                        let mut sc = ch.walk();
                        let inner = ch
                            .children(&mut sc)
                            .find(|x| {
                                matches!(
                                    x.kind(),
                                    "interpreted_string_literal_content" | "string_fragment"
                                )
                            })
                            .map(|t| text(t, src).to_string())
                            .unwrap_or_else(|| text(ch, src).trim_matches('"').to_string());
                        path = Some(inner);
                    }
                    _ => {}
                }
            }
            if let Some(p) = path {
                ctx.out.edges.push(Edge {
                    kind: EdgeKind::Imports,
                    src: ctx.package.clone(),
                    dst: p.clone(),
                    confidence: 1.0,
                });
                let alias_name =
                    alias.unwrap_or_else(|| p.rsplit('/').next().unwrap_or(&p).to_string());
                if !alias_name.is_empty() && alias_name != "_" && alias_name != "." {
                    ctx.aliases.insert(alias_name, p);
                }
            }
            continue;
        }
        let mut c = node.walk();
        for ch in node.children(&mut c) {
            stack.push(ch);
        }
    }
}
