import ast
import yaml

class SecurityEngine:
    def __init__(self, rules_file):
        with open(rules_file, 'r') as f:
            self.rules = yaml.safe_load(f)['rules']

    def scan(self, code):
        tree = ast.parse(code)
        findings = []

        for node in ast.walk(tree):
            # 1. Detect Sinks (Dangerous Function Calls)
            if isinstance(node, ast.Call):
                findings.extend(self._check_sinks(node))
                
        return findings

    def _check_sinks(self, node):
        detected = []
        name = self._get_name(node.func)
        
        for rule in self.rules:
            if name in rule['sinks']:
                detected.append({
                    "id": rule['id'],
                    "message": rule['message'],
                    "line": node.lineno,
                    "severity": rule['severity']
                })
        return detected

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