"""Security scanning for foreign skill code.

Scans Python source code for red flags before allowing installation
from the ALP network. Checks for code injection, dangerous system calls,
file deletion, and suspicious network activity.
"""

from __future__ import annotations

import re


def scan_for_risks(code: str) -> list[str]:
    """Scan skill code for security red flags before installation.

    Args:
        code: Python source code to scan.

    Returns:
        List of human-readable risk descriptions. Empty means clean.
    """
    risks: list[str] = []

    if "eval(" in code:
        risks.append("\u26a0\ufe0f  Uses eval() \u2014 potential code injection")
    if "exec(" in code:
        risks.append("\u26a0\ufe0f  Uses exec() \u2014 potential code injection")
    if "subprocess" in code and "shell=True" in code:
        risks.append("\u26a0\ufe0f  Shell execution with shell=True")
    if "os.system(" in code:
        risks.append("\u26a0\ufe0f  Direct system command execution")
    if any(s in code for s in ["rm -rf", "rmdir", "shutil.rmtree"]):
        risks.append("\u26a0\ufe0f  File deletion operations")
    if "__import__(" in code:
        risks.append("\u26a0\ufe0f  Dynamic import \u2014 could load anything")
    if "open(" in code and ("/etc/" in code or "/root/" in code or "C:\\" in code):
        risks.append("\u26a0\ufe0f  Accesses sensitive system paths")

    # Check for network calls to non-standard URLs
    safe_domains = [
        "github.com",
        "pypi.org",
        "googleapis.com",
        "api.telegram.org",
        "duckduckgo.com",
        "amazon.",
        "google.com",
    ]
    urls = re.findall(r"https?://[^\s'\"]+", code)
    for url in urls:
        if not any(safe in url for safe in safe_domains):
            risks.append(f"\u26a0\ufe0f  Network call to: {url}")

    return risks
