import subprocess
import json
import typing

class ImmuneDaemon:
    def __init__(self):
        self.alerts = []

    def scan_dependencies(self, project_path: str = ".") -> typing.List[str]:
        """Runs a real safety check on the project environment."""
        found_alerts = []
        try:
            result = subprocess.run(
                ["safety", "check", "--json"],
                capture_output=True,
                text=True,
                check=False
            )
            if result.stdout.strip():
                try:
                    data = json.loads(result.stdout)
                    vulns = data.get("vulnerabilities", [])
                    for v in vulns:
                        found_alerts.append(f"Vulnerability found: {v.get('package_name')} - {v.get('vulnerability_id')}")
                except json.JSONDecodeError:
                    pass
        except Exception as e:
            found_alerts.append(f"Safety check failed: {e}")
        return found_alerts
        
    def scan_codebase(self, project_path: str = ".") -> typing.List[str]:
        """Runs Bandit to find security issues in Python code."""
        found_alerts = []
        try:
            result = subprocess.run(
                ["bandit", "-r", project_path, "-f", "json"],
                capture_output=True,
                text=True,
                check=False
            )
            if result.stdout.strip():
                try:
                    data = json.loads(result.stdout)
                    metrics = data.get("metrics", {}).get("_totals", {})
                    high = metrics.get("SEVERITY.HIGH", 0)
                    med = metrics.get("SEVERITY.MEDIUM", 0)
                    if high > 0 or med > 0:
                        found_alerts.append(f"Bandit found issues: {high} High, {med} Medium severity.")
                except json.JSONDecodeError:
                    pass
        except Exception as e:
            found_alerts.append(f"Bandit scan failed: {e}")
        return found_alerts

    def fuzz_local_ports(self) -> typing.List[str]:
        """Scans local listening ports using netstat to identify exposed services."""
        found_alerts = []
        try:
            result = subprocess.run(
                ["netstat", "-an"],
                capture_output=True,
                text=True,
                check=False
            )
            listening = [line.strip() for line in result.stdout.splitlines() if "LISTENING" in line or "LISTEN" in line]
            found_alerts.append(f"Detected {len(listening)} open listening ports.")
            if listening:
                found_alerts.append(f"Sample: {listening[0]}")
        except Exception as e:
            found_alerts.append(f"Port scan failed: {e}")
        return found_alerts
