"""
SentinelScan - Vulnerability Checks Module
Provides functionality for basic vulnerability detection.
"""

import requests
import socket
from typing import List

# ============================================================
# Configuration
# ============================================================

DEFAULT_TIMEOUT = 2.0
COMMON_ADMIN_PATHS = [
    "admin", "login", "dashboard", "cpanel", "administrator",
    "user", "portal", "manage", "system", "root"
]

COMMON_FILES = [
    "robots.txt", "sitemap.xml", ".git/", "config.php", "backup.zip"
]

# ============================================================
# Helper Functions
# ============================================================

def check_admin_panels(domain: str) -> List[str]:
    """
    Check for common admin panels.
    """
    results = []
    print(f"[*] Checking admin panels on {domain}...")
    for path in COMMON_ADMIN_PATHS:
        url = f"http://{domain}/{path}"
        try:
            r = requests.get(url, timeout=DEFAULT_TIMEOUT)
            if r.status_code < 400:
                results.append(f"[+] Found admin panel: {url} (Status {r.status_code})")
        except Exception:
            continue
    return results


def check_sensitive_files(domain: str) -> List[str]:
    """
    Check for sensitive files.
    """
    results = []
    print(f"[*] Checking sensitive files on {domain}...")
    for path in COMMON_FILES:
        url = f"http://{domain}/{path}"
        try:
            r = requests.get(url, timeout=DEFAULT_TIMEOUT)
            if r.status_code < 400:
                results.append(f"[+] Found sensitive file: {url} (Status {r.status_code})")
        except Exception:
            continue
    return results


def check_open_ports(domain: str, ports: List[int]) -> List[str]:
    """
    Check if specific ports are open.
    """
    results = []
    print(f"[*] Checking open ports on {domain}...")
    for port in ports:
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.settimeout(DEFAULT_TIMEOUT)
            result = sock.connect_ex((domain, port))
            if result == 0:
                results.append(f"[+] Port {port} OPEN on {domain}")
            sock.close()
        except Exception as e:
            results.append(f"[!] Error checking port {port}: {e}")
    return results


# ============================================================
# Security Header Checks
# ============================================================

def check_security_headers(domain: str) -> List[str]:
    """
    Check for missing security headers.
    """
    results = []
    urls = [f"http://{domain}", f"https://{domain}"]
    for url in urls:
        try:
            r = requests.get(url, timeout=DEFAULT_TIMEOUT)
            headers = r.headers
            if "X-Frame-Options" not in headers:
                results.append(f"[!] {url} missing X-Frame-Options")
            if "Content-Security-Policy" not in headers:
                results.append(f"[!] {url} missing CSP")
            if "Strict-Transport-Security" not in headers:
                results.append(f"[!] {url} missing HSTS")
        except Exception as e:
            results.append(f"[!] Failed to fetch headers from {url}: {e}")
    return results


# ============================================================
# Extended Vulnerability Checks
# ============================================================

def check_directory_listing(domain: str, paths: List[str] = ["uploads", "files", "images"]) -> List[str]:
    """
    Check for directory listing enabled.
    """
    results = []
    for path in paths:
        url = f"http://{domain}/{path}/"
        try:
            r = requests.get(url, timeout=DEFAULT_TIMEOUT)
            if "Index of" in r.text:
                results.append(f"[!] Directory listing enabled: {url}")
        except Exception:
            continue
    return results


def check_default_pages(domain: str) -> List[str]:
    """
    Check for default server pages.
    """
    results = []
    urls = [f"http://{domain}", f"https://{domain}"]
    for url in urls:
        try:
            r = requests.get(url, timeout=DEFAULT_TIMEOUT)
            if "Apache2 Ubuntu Default Page" in r.text:
                results.append(f"[!] Default Apache page found at {url}")
            if "IIS Windows Server" in r.text:
                results.append(f"[!] Default IIS page found at {url}")
        except Exception:
            continue
    return results


def check_cve_patterns(domain: str) -> List[str]:
    """
    Basic CVE pattern checks (very simplified).
    """
    results = []
    urls = [f"http://{domain}", f"https://{domain}"]
    for url in urls:
        try:
            r = requests.get(url, timeout=DEFAULT_TIMEOUT)
            if "wp-content" in r.text:
                results.append(f"[!] WordPress detected at {url} (check WP CVEs)")
            if "Joomla" in r.text:
                results.append(f"[!] Joomla detected at {url} (check Joomla CVEs)")
        except Exception:
            continue
    return results


# ============================================================
# Main Function
# ============================================================

def run_checks(domain: str) -> List[str]:
    """
    Run all vulnerability checks.
    """
    results = []
    results.extend(check_admin_panels(domain))
    results.extend(check_sensitive_files(domain))
    results.extend(check_open_ports(domain, [21, 22, 23, 80, 443, 3306]))
    results.extend(check_security_headers(domain))
    results.extend(check_directory_listing(domain))
    results.extend(check_default_pages(domain))
    results.extend(check_cve_patterns(domain))
    return results


# ============================================================
# Testing Stub
# ============================================================

if __name__ == "__main__":
    target_domain = "example.com"
    vuln_results = run_checks(target_domain)
    for r in vuln_results:
        print(r)
