import ast
import yaml
import os

class CoreScanner:
    def __init__(self, rules_path=None):
        if rules_path is None:
            rules_path = os.path.join(os.path.dirname(__file__), "rules.yaml")
        
        with open(rules_path, "r") as f:
            self.rules = yaml.safe_load(f)["rules"]

    def analyze_source(self, code_content):
        """Main entry point for scanning code strings."""
        try:
            tree = ast.parse(code_content)
            findings = []
            
            for node in ast.walk(tree):
                # Check for dangerous function calls (Sinks)
                if isinstance(node, ast.Call):
                    findings.extend(self._check_node(node))
            return findings
        except Exception as e:
            return [{"error": str(e)}]

    def _check_node(self, node):
        issues = []
        # Logic to match node against rules.yaml
        func_name = self._get_func_name(node)
        for rule in self.rules:
            if func_name in rule["sinks"]:
                issues.append({
                    "id": rule["id"],
                    "severity": rule["severity"],
                    "line": node.lineno,
                    "message": rule["message"]
                })
        return issues

    def _get_func_name(self, node):
        if isinstance(node.func, ast.Name):
            return node.func.id
        elif isinstance(node.func, ast.Attribute):
            return node.func.attr
        return ""