"""Dependency resolver — lightweight import analysis for context enrichment.

Parses Python ``import`` / ``from … import …`` statements to identify
modules that may be relevant to a vulnerability.
"""

from __future__ import annotations

import logging
import re
from pathlib import Path

from secagent.utils.file_loader import read_file_text

logger = logging.getLogger(__name__)

_IMPORT_RE = re.compile(
    r"^\s*(?:from\s+([\w.]+)\s+import|import\s+([\w.,\s]+))", re.MULTILINE
)


def resolve_imports(file_path: str | Path) -> list[str]:
    """Return a list of module names imported by *file_path*.

    Only top-level ``import`` and ``from … import`` statements are
    considered.  This is intentionally simple — full AST parsing would be
    overkill for the context-enrichment use case.

    Parameters
    ----------
    file_path:
        Path to a Python source file.

    Returns
    -------
    list[str]
        Sorted, deduplicated list of imported module names.
    """
    content = read_file_text(file_path)
    if not content:
        return []

    modules: set[str] = set()
    for match in _IMPORT_RE.finditer(content):
        from_mod = match.group(1)
        import_mods = match.group(2)
        if from_mod:
            modules.add(from_mod.split(".")[0])
        if import_mods:
            for mod in import_mods.split(","):
                modules.add(mod.strip().split(".")[0].split(" ")[0])

    return sorted(modules)
