"""
SentinelScan - Web Reconnaissance Module
Provides functionality for analyzing web servers and technologies.
"""

import requests
import ssl
import socket
from urllib.parse import urlparse
from typing import List, Dict

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

DEFAULT_TIMEOUT = 2.0
USER_AGENT = "SentinelScan/1.0"

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

def fetch_headers(url: str) -> Dict[str, str]:
    """
    Fetch HTTP headers from a given URL.
    Always return a plain dict for consistency.
    """
    try:
        r = requests.get(url, timeout=DEFAULT_TIMEOUT, headers={"User-Agent": USER_AGENT})
        return dict(r.headers)   # normalize CaseInsensitiveDict → dict
    except Exception as e:
        return {"Error": str(e)}


def analyze_headers(domain: str) -> List[str]:
    """
    Analyze headers for a given domain.
    """
    results = []
    urls = [f"http://{domain}", f"https://{domain}"]

    for url in urls:
        print(f"[*] Fetching headers from {url}...")
        headers = fetch_headers(url)
        if "Error" in headers:
            results.append(f"[!] Failed to fetch {url}: {headers['Error']}")
            continue

        results.append(f"[+] Headers for {url}:")
        for k, v in headers.items():
            results.append(f"    {k}: {v}")

        # Security header checks
        if "X-Frame-Options" not in headers:
            results.append("[!] Missing X-Frame-Options (Clickjacking risk)")
        if "Content-Security-Policy" not in headers:
            results.append("[!] Missing Content-Security-Policy (XSS risk)")
        if "Strict-Transport-Security" not in headers:
            results.append("[!] Missing HSTS (SSL stripping risk)")

    return results


def detect_technologies(headers: Dict[str, str]) -> List[str]:
    """
    Detect technologies based on headers.
    """
    tech = []
    server = headers.get("Server")
    powered = headers.get("X-Powered-By")

    if server:
        tech.append(f"[+] Server: {server}")
    if powered:
        tech.append(f"[+] Powered by: {powered}")

    if powered and "php" in powered.lower():
        tech.append("[+] Detected PHP application")
    if powered and "asp" in powered.lower():
        tech.append("[+] Detected ASP.NET application")

    return tech


# ============================================================
# SSL/TLS Analysis
# ============================================================

def ssl_info(domain: str) -> List[str]:
    """
    Retrieve SSL certificate information.
    """
    results = []
    try:
        ctx = ssl.create_default_context()
        with ctx.wrap_socket(socket.socket(), server_hostname=domain) as s:
            s.settimeout(DEFAULT_TIMEOUT)
            s.connect((domain, 443))
            cert = s.getpeercert()
            results.append(f"[+] SSL Certificate for {domain}:")
            results.append(f"    Subject: {cert.get('subject')}")
            results.append(f"    Issuer: {cert.get('issuer')}")
            results.append(f"    Valid From: {cert.get('notBefore')}")
            results.append(f"    Valid Until: {cert.get('notAfter')}")
    except Exception as e:
        results.append(f"[!] SSL analysis failed: {e}")
    return results


# ============================================================
# Extended Features
# ============================================================

def check_cors(headers: Dict[str, str]) -> str:
    """
    Check for CORS misconfigurations.
    """
    origin = headers.get("Access-Control-Allow-Origin")
    if origin == "*":
        return "[!] CORS allows all origins (security risk)"
    elif origin:
        return f"[+] CORS restricted to: {origin}"
    return "[!] No CORS policy found"


def check_cookie_security(headers: Dict[str, str]) -> List[str]:
    """
    Check cookies for security flags.
    """
    results = []
    cookies = headers.get("Set-Cookie")
    if cookies:
        if "HttpOnly" not in cookies:
            results.append("[!] Cookie missing HttpOnly flag")
        if "Secure" not in cookies:
            results.append("[!] Cookie missing Secure flag")
    else:
        results.append("[!] No cookies set")
    return results


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

def run_web_recon(domain: str) -> List[str]:
    """
    Run full web reconnaissance on a domain.
    """
    results = []
    urls = [f"http://{domain}", f"https://{domain}"]

    for url in urls:
        headers = fetch_headers(url)
        if "Error" in headers:
            results.append(f"[!] Failed to fetch {url}: {headers['Error']}")
            continue

        results.append(f"[+] Analyzing {url}...")
        results.extend(detect_technologies(headers))
        cors_result = check_cors(headers)
        results.append(cors_result)
        results.extend(check_cookie_security(headers))

    # SSL info
    results.extend(ssl_info(domain))

    return results


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

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

    recon_results = run_web_recon(target_domain)
    for r in recon_results:
        print(r)
