"""Auto-exploitation module for safe verification of takeover vulnerabilities."""
import asyncio
from typing import Dict, Optional
import aiohttp

from reclaimor.config import Config
from reclaimor.exploit.providers.github import GitHubExploiter
from reclaimor.exploit.providers.heroku import HerokuExploiter
from reclaimor.exploit.providers.s3 import S3Exploiter
from reclaimor.exploit.providers.netlify import NetlifyExploiter
from reclaimor.utils.logger import setup_logger

logger = setup_logger(__name__)


class Exploiter:
    """
    Auto-exploitation engine for verifying subdomain takeover vulnerabilities.
    
    IMPORTANT: This performs actual takeover attempts for verification.
    Only use on domains you own or have explicit authorization to test.
    """
    
    def __init__(self, config: Config):
        self.config = config
        self.exploiters = {
            "GitHub Pages": GitHubExploiter(config),
            "Heroku": HerokuExploiter(config),
            "AWS S3": S3Exploiter(config),
            "Netlify": NetlifyExploiter(config),
        }
    
    async def attempt_takeover(
        self,
        domain: str,
        provider: Optional[str],
        dns_info: Dict,
        http_info: Dict,
    ) -> Dict:
        """
        Attempt to take over a vulnerable subdomain for verification.
        
        Args:
            domain: Target domain
            provider: Detected provider name
            dns_info: DNS check results
            http_info: HTTP check results
        
        Returns:
            Dict with:
                - success: bool
                - method: str (how takeover was achieved)
                - proof: str (verification token or URL)
                - cleanup: callable to undo takeover
                - error: str or None
        """
        result = {
            "success": False,
            "method": None,
            "proof": None,
            "cleanup": None,
            "error": None,
        }
        
        if not provider or provider not in self.exploiters:
            result["error"] = f"No exploiter available for provider: {provider}"
            return result
        
        logger.info(f"Attempting takeover of {domain} via {provider}")
        
        try:
            exploiter = self.exploiters[provider]
            exploit_result = await exploiter.exploit(domain, dns_info, http_info)
            
            if exploit_result.get("success"):
                logger.warning(f"✓ Successfully took over {domain} via {provider}")
                result.update(exploit_result)
                
                # Auto-cleanup after verification (optional)
                if self.config.auto_exploit and exploit_result.get("cleanup"):
                    logger.info(f"Auto-cleaning up takeover of {domain}")
                    await asyncio.sleep(5)  # Wait to ensure verification
                    await exploit_result["cleanup"]()
            else:
                result["error"] = exploit_result.get("error", "Exploitation failed")
        
        except Exception as e:
            logger.error(f"Exploitation error for {domain}: {e}")
            result["error"] = str(e)
        
        return result
